Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Java

Validating XML Document using XML Schema using XMLBeans

3.00/5 (2 votes)
26 Aug 2010GPL31 min read 39.9K   478  
XMLBeans for Java can be used for validating XML Document based on some schema

Introduction

XML documents are normally validated using DTD or XML schemas. XML Schemas are simpler and yet more powerful to validate any XML document. Java has an inbuilt Xerces parser which can be used for validation of any XML doc against a schema but it tends to be slow. XMLBeans is a Java XML library to perform operations like parsing, validating, marshalling, unmarshalling, etc.

This article demonstrates how we can validate XML doc against XML schema using XMLBeans.

Background

A very good tutorial for XML schema is available at W3Schools. XMLBeans is available here. The library can be used to validate an XML document against multiple schema documents.

Using the Code

The sample code has been developed using Maven and all you need is to download maven and install to get the application running.

From the project folder run command:

mvn clean install

The following line of code parses the XML schema document itself and loads it:

Java
XmlObject parsedSchema = XmlObject.Factory.parse(schemaStream , 
new XmlOptions().setLoadLineNumbers().setLoadMessageDigest());

This is how you create a Schema Type System for validation:

Java
SchemaTypeLoader loader = XmlBeans.compileXsd(schemas, null, 
   new XmlOptions().setErrorListener(null).setCompileDownloadUrls().
	setCompileNoPvrRule());

This is how you parse the XML document using the type system to get XML object:

Java
XmlObject object = loader.parse(xmlStream, 

null, new XmlOptions().setLoadLineNumbers(XmlOptions.LOAD_LINE_NUMBERS_END_ELEMENT));

And finally the validation:

Java
object.validate(new XmlOptions().setErrorListener(errorList)); 

To invoke the validation, we need to pass 3 arguments:

  1. The schema file
  2. The XML document
  3. ArrayList<String> to trap the errors during validation

Also note that we can use multiple schemas to validate but this example only shows validation using one schema.

The schema or document can be provided from a variety of sources including file, inputstream or XML Node.

History

  • 26th August, 2010: Initial post

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)