XML Tutorials - Herong's Tutorial Examples - v5.25, by Herong Yang
XSD Schema Validator on XML DOM Object
This section provides a tutorial example on how to load a XSD schema, create an XSD validator and validate an XML DOM object.
If you want to validate an XML presented as a DOM object against an XSD schema, you can load the XSD file and create a Schema object first. Then create a Validator object to validate the DOM object.
Here is a tutorial example program called XsdSchemaDomValidatorWithErrorHandler.java that validates an XML file against an XSD file using the DOM interface:
/* XsdSchemaDomValidatorWithErrorHandler.java * Copyright (c) 2014-2018 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; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.ErrorHandler; class XsdSchemaDomValidatorWithErrorHandler { private static int errorCount = 0; public static void main(String[] a) { if (a.length<2) { System.out.println("Usage:"); System.out.println("java XsdSchemaDomValidatorWithErrorHandler " + "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()); // setting my own error handler validator.setErrorHandler(new MyErrorHandler()); // validating the document against the schema validator.validate(new DOMSource(document)); System.out.println(); if (errorCount>0) { System.out.println("Failed with errors: "+errorCount); } else { System.out.println("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; } static class MyErrorHandler implements ErrorHandler { public void fatalError( SAXParseException e ) throws SAXException { System.out.println(e.toString()); throw e; } public void error( SAXParseException e ) throws SAXException { System.out.println(e.toString()); errorCount++; // continue with validation process // throw e; } public void warning( SAXParseException e ) throws SAXException { System.out.println(e.toString()); } } }
In order to test XsdSchemaDomValidatorWithErrorHandler.java, here is a sample XSD file, 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>
Here is an XML file, first_html.xml, that conforms with the above XSD:
<?xml version="1.0" encoding="utf-8"?> <html> <body>My first HTML document in XML format.</body> </html>
Here is test result with JDK (Java Development Kit).
herong> java XsdSchemaDomValidatorWithErrorHandler \ first_html.xsd first_html.xml Validator Class: com.sun.org.apache.xerces.internal.jaxp.validation.ValidatorImpl Passed.
Cool. My validator, XsdSchemaDomValidatorWithErrorHandler.java, works.
Table of Contents
Introduction of XML (eXtensible Markup Language)
DOM (Document Object Model) Programming Interface
SAX (Simple API for XML) Programming Interface
DTD (Document Type Definition) Introduction
Validating an XML Document against the Specified DTD Document Type
XSD (XML Schema Definition) Introduction
►Validating XML Documents Against Specified XML Schemas
►XSD Schema Validator on XML DOM Object
XSD Schema Validator on XML DOM Object - Errors
XSD Schema Validator on XML SAX Object
SAXParseException - 'xsi:noNamespaceSchemaLocation' Not Allowed
Validating XML Linked with XSD using XMLReader
XSL (Extensible Stylesheet Language) Introduction
XSLT (XSL Transformations) Introduction
XSLT Elements as Programming Statements
Control and Generate XML Element in the Result
PHP Extensions for XML Manipulation
Processing XML with Python Scripts
XML Tools Plugin for Notepad++
XML Plugin Packages for Atom Editor