XSD Tutorials - Herong's Tutorial Examples - Version 5.10, by Dr. Herong Yang

XSD Schema XML DOM Validator - XsdSchemaDomValidator.java

This section describes a tutorial example on how to create a Validator instance from an XSD Schema instance to validate an XML file using the JAXP DOM interface.

After creating an XSD Schema instance from the XSD schema file, we are ready to create a Validator instance from the schema instance. This Validator instance can then be used to validate an XML file represented with the DOM interface or the SAX interface.

Let's try the DOM interface first. If you need to learn DOM interface, you can read the XML file DOM parser tutorial example described in another chapter of this book.

Here is a tutorial example program called XsdSchemaDomValidator.java that validates an XML file against an XSD file using the DOM interface:

/*
 * XsdSchemaDomValidator.java
 - Copyright (c) 2013, HerongYang.com, All Rights Reserved.
 */
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Schema;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import javax.xml.validation.Validator;
import javax.xml.transform.dom.DOMSource;
import java.io.File;
class XsdSchemaDomValidator {
  public static void main(String[] a) {
    if (a.length<2) {
      System.out.println("Usage:");
      System.out.println("java XsdSchemaValidator schema_file_name "
        + "xml_file_name");
    } else {
      String schemaName = a[0];
      String xmlName = a[1];
      Schema schema = loadSchema(schemaName);
      Document document = parseXmlDom(xmlName);
      validateXml(schema, document);
    }
  }
  public static void validateXml(Schema schema, Document document) {
    try {
      // creating a Validator instance
      Validator validator = schema.newValidator();
      System.out.println();
      System.out.println("Validator Class: "
        + validator.getClass().getName());

      // validating the document against the schema
      validator.validate(new DOMSource(document));
      System.out.println();
      System.out.println("Validation passed.");

    } catch (Exception e) {
      // catching all validation exceptions
      System.out.println();
      System.out.println(e.toString());
    }
  }
  public static Schema loadSchema(String name) {
    Schema schema = null;
    try {
      String language = XMLConstants.W3C_XML_SCHEMA_NS_URI;
      SchemaFactory factory = SchemaFactory.newInstance(language);
      schema = factory.newSchema(new File(name));
    } catch (Exception e) {
      System.out.println(e.toString());
    }
    return schema;
  }
  public static Document parseXmlDom(String name) {
    Document document = null;
    try {
      DocumentBuilderFactory factory 
         = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();
      document = builder.parse(new File(name));
    } catch (Exception e) {
      System.out.println(e.toString());
    }
    return document;
  }
}

As the first test, let's try to validate the following simple XML file, first_html.xml, against the simple XSD schema file, first_html.xsd:

>type first_html.xsd
<?xml version = "1.0" encoding = "utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
  elementFormDefault="qualified" attributeFormDefault="unqualified">
 <xs:element name="html" type="htmlType"/>
 <xs:complexType name="htmlType">
  <xs:sequence>
   <xs:element name="body" type="xs:string"/>
  </xs:sequence>
 </xs:complexType>
</xs:schema>

>type first_html.xml
<?xml version = "1.0" encoding = "utf-8"?>
<html>
<body>My first HTML document in XML format.</body>
</html>

>javac XsdSchemaDomValidator.java

>java XsdSchemaDomValidator first_html.xsd first_html.xml

Validator Class: com.sun.org.apache.xerces.internal.jaxp
   .validation.ValidatorImpl

Validation passed.

The output shows that:

  • The default implementation class of the Validator class is also from the Apache Xerces project.
  • The validation passed successfully. No exceptions raised.

Last update: 2013.

Table of Contents

 About This Book

 Introduction to XML Schema

 XML Editor and Schema Processor - XMLPad

 Java API for XML Processing - JAXP

JAXP - XML Schema (XSD) Validation

 Standard Steps to Validate XML Documents Against a Schema

 XSD Schema File Loader - XsdSchemaLoader.java

 XSD Schema File Loading Errors

XSD Schema XML DOM Validator - XsdSchemaDomValidator.java

 XSD Schema XML DOM Validation Errors

 XSD Schema XML DOM Validator with Error Handler

 XSD Schema XML SAX Validator - XsdSchemaSaxValidator.java

 XSD Schema XML SAX Validation Errors

 XSD Schema XML SAX Validator with Error Handler

 XSD Schema XML Validator - Final Version

 Xerces2 Java Parser - Java API of XML Parsers

 Using Xerces2 Java API

 XML Schema Language - Basics

 Introduction of XSD Built-in Datatypes

 "string" and Its Derived Datatypes

 "decimal" and Its Derived Datatypes

 "dateTime" and Its Related Datatypes

 Miscellaneous Built-in Datatypes

 Facets, Constraining Facets and Restriction Datatypes

 "simpleType" - Defining Your Own Simple Datatypes

 Complex Element Declaration

 Identity-Constraints: unique, key and keyref

 Assertion as Custom Validation Rules

 XML Schema Location and Namespace in XML Documents

 Overriding Element Types in XML Documents

 Linking Multiple Schema Documents Together

 Glossary

 References

 PDF Printing Version

XSD Schema XML DOM Validator - XsdSchemaDomValidator.java - Updated in 2014, by Dr. Herong Yang