Schema Validation using SAX and DOM Parser with Oracle JDeveloper - XDK 11g

Exclusive offer: get 50% off this eBook here
Processing XML documents with Oracle JDeveloper 11g

Processing XML documents with Oracle JDeveloper 11g — Save 50%

Create, validate, and transform XML documents with Oracle's JDeveloper IDE using this book and eBook

$32.99    $16.50
by Deepak Vohra | March 2009 | Oracle

XDK 11g provides the Simple API for XML (SAX) and the Document Object Model (DOM) API for parsing an XML document. XDK 11g is included with JDeveloper 11g. XDK 11g parsers DOMParser and SAXParser may be configured for schema validation. In the previous article we discussed validating an XML document with an XML schema using XSDValidator. In this article by Deepak Vohra, we will discuss the procedure to validate an XML document with the SAXParser and the DOMParser.

The choice of validation method depends on the additional functionality required in the validation application. SAXParser is recommended if SAX parsing event notification is required in addition to validation with a schema. DOMParser is recommended if the DOM tree structure of an XML document is required for random access and modification of the XML document.

Schema validation with a SAX parser

In this section we shall validate the example XML document catalog.xml with XML schema document catalog.xsd, with the SAXParser class. Import the oracle.xml.parser.schema and oracle.xml.parser.v2 packages.

Creating a SAX parser

Create a SAXParser object and set the validation mode of the SAXParser object to SCHEMA_VALIDATION, as shown in the following listing:

SAXParser saxParser=new SAXParser();
saxParser.setValidationMode(XMLParser.SCHEMA_VALIDATION);

The different validation modes that may be set on a SAXParser are discussed in the following table; but we only need the SCHEMA-based validation modes:

Validation Mode

Description

NONVALIDATING

The parser does not validate the XML document.

PARTIAL_VALIDATION

The parser validates the complete or a partial XML document with a DTD or an XML schema if specified.

DTD_VALIDATION

The parser validates the XML document with a DTD if any.

SCHEMA_VALIDATION

The parser validates the XML document with an XML schema if any specified.

SCHEMA_LAX_VALIDATION

Validates the complete or partial XML document with an XML schema if the parser is able to locate a schema. The parser does not raise an error if a schema is not found.

SCHEMA_STRICT_VALIDATION

Validates the complete XML document with an XML schema if the parser is able to find a schema. If the parser is not able find a schema or if the XML document does not conform to the schema, an error is raised.

Next, create an XMLSchema object from the schema document with which an XML document is to be validated. An XMLSchema object represents the DOM structure of an XML schema document and is created with an XSDBuilder class object. Create an XSDBuilder object and invoke the build(InputSource) method of the XSDBuilder object to obtain an XMLSchema object. The InputSource object is created with an InputStream object created from the example XML schema document, catalog.xsd. As discussed before, we have used an InputSource object because most SAX implementations are InputSource based. The procedure to obtain an XMLSchema object is shown in the following listing:

XSDBuilder builder = new XSDBuilder();
InputStream inputStream=new FileInputStream(new File("catalog.xsd"));
InputSource inputSource=new InputSource(inputStream);
XMLSchema schema = builder.build(inputSource);

Set the XMLSchema object on the SAXParser object with setXMLSchema(XMLSchema) method:

saxParser.setXMLSchema(schema);

Setting the error handler

As in the previous section, define an error handling class, CustomErrorHandler that extends DefaultHandler class. Create an object of type CustomErrorHandler, and register the ErrorHandler object with the SAXParser as shown here:

CustomErrorHandler errorHandler = new CustomErrorHandler();
saxParser.setErrorHandler(errorHandler);

Validating the XML document

The SAXParser class extends the XMLParser class, which provides the overloaded parse methods discussed in the following table to parse an XML document:

Method

Description

parse(InputSource in)

Parses an XML document from an org.xml.sax.InputSouce object. The InputSource-based parse method is the preferred method because SAX parsers convert the input to InputSource no matter what the input type is.

parse(java.io.InputStream in)

Parses an XML document from an InputStream.

parse(java.io.Reader r)

Parses an XML document from a Reader.

parse(java.lang.String in)

Parses an XML document from a String URL for the XML document.

parse(java.net.URL url)

Parses an XML document from the specified URL object for the XML document.

Create an InputSource object from the XML document to be validated, and parse the XML document with the parse(InputSource) object:

InputStream inputStream=new FileInputStream(new
File("catalog.xml"));
InputSource inputSource=new InputSource(inputStream);
saxParser.parse(inputSource);

Running the Java application

The validation application SAXValidator.java is listed in the following listing with additional explanations:

  1. First we declare the import statements for the classes that we need.
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import oracle.xml.parser.schema.*;
    import oracle.xml.parser.v2.*;
    import java.io.IOException;
    import java.io.InputStream;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.xml.sax.helpers.DefaultHandler;
    import org.xml.sax.InputSource;
  2. We define the Java class SAXValidator for SAX validation.
    public class SAXValidator {
  3. In the Java class we define a method validateXMLDocument.
    public void validateXMLDocument(InputSource input) {
    try {
  4. In the method we create a SAXParser and set the XML schema on the SAXParser.
    SAXParser saxParser = new SAXParser();
    saxParser.setValidationMode(XMLParser.SCHEMA_VALIDATION);
    XMLSchema schema=getXMLSchema();
    saxParser.setXMLSchema(schema);
  5. To handle errors we create a custom error handler. We set the error handler on the SAXParser object and parse the XML document to be validated and also output validation errors if any.
    CustomErrorHandler errorHandler = new CustomErrorHandler();
    saxParser.setErrorHandler(errorHandler);
    saxParser.parse(input);
    if (errorHandler.hasValidationError == true) {
    System.err.println("XML Document has
    Validation Error:" + errorHandler.saxParseException.getMessage());
    } else {
    System.out.println("XML Document validates
    with XML schema");
    }
    } catch (IOException e) {
    System.err.println("IOException " + e.getMessage());
    } catch (SAXException e) {
    System.err.println("SAXException " + e.getMessage());
    }
    }
  6. We add the Java method getXMLSchema to create an XMLSchema object.
    try {
    XSDBuilder builder = new XSDBuilder();
    InputStream inputStream =
    new FileInputStream(new File("catalog.xsd"));
    InputSource inputSource = new
    InputSource(inputStream);
    XMLSchema schema = builder.build(inputSource);
    return schema;
    } catch (XSDException e) {
    System.err.println("XSDException " + e.getMessage());
    } catch (FileNotFoundException e) {
    System.err.println("FileNotFoundException " +
    e.getMessage());
    }
    return null;
    }
  7. We define the main method in which we create an instance of the SAXValidator class and invoke the validateXMLDocument method.
    public static void main(String[] argv) {
    try {
    InputStream inputStream =
    new FileInputStream(new File("catalog.xml"));
    InputSource inputSource=new InputSource(inputStream);
    SAXValidator validator = new SAXValidator();
    validator.validateXMLDocument(inputSource);
    } catch (FileNotFoundException e) {
    System.err.println("FileNotFoundException " +
    e.getMessage());
    }
    }
  8. Finally, we define the custom error handler class as an inner class CustomErrorHandler to handle validation errors.
    private class CustomErrorHandler extends DefaultHandler {
    protected boolean hasValidationError = false;
    protected SAXParseException saxParseException = null;
    public void error(SAXParseException exception)
    {
    hasValidationError = true;
    saxParseException = exception;
    }
    public void fatalError(SAXParseException exception)
    {
    hasValidationError = true;
    saxParseException = exception;
    }
    public void warning(SAXParseException exception)
    {
    }
    }
    }

Copy the SAXValidator.java application to SAXValidator.java in the SchemaValidation project. To demonstrate error handling, add a title element to the journal element.

To run the SAXValidator.java application, right-click on SAXValidator.java in Application Navigator, and select Run. A validation error gets outputted. The validation error indicates that the title element is not expected.

Processing XML documents with Oracle JDeveloper 11g

Processing XML documents with Oracle JDeveloper 11g Create, validate, and transform XML documents with Oracle's JDeveloper IDE using this book and eBook
Published: May 2009
eBook Price: $32.99
Book Price: $54.99
See more
Select your format and quantity:

Schema validation with a DOM parser

In this section, we shall validate the example XML document, catalog.xml, against catalog.xsd with the DOMParser class. The procedure to validate with a DOMParser is the same as with a SAXParser, except that the parser class is different. First, import the oracle.xml.parser.schema and the oracle.xml.parser.v2 packages.

Creating a DOM parser

Create a DOMParser object and set validation mode to SCHEMA_VALIDATION, as shown in the following listing:

DOMParser domParser=new DOMParser();
domParser.setValidationMode(XMLParser.SCHEMA_VALIDATION);

Create an XMLSchema object, which represents the DOM structure of an XML schema document, from the example schema document. To create an XMLSchema object, first create an XSDBuilder object. Next, create an InputStream object from catalog.xsd and subsequently create an InputSource object from the InputStream object. Create an XMLSchema object with the build(InputSource) method of the XSDBuilder class. The procedure to obtain an XMLSchema object is shown in the following listing:

XSDBuilder builder = new XSDBuilder();
InputStream inputStream=new FileInputStream(new File("catalog.xsd"));
InputSource inputSource=new InputSource(inputStream);
XMLSchema schema = builder.build(inputSource);

Set the XMLSchema object on the DOMParser object with the setXMLSchema(XMLSchema) method:

domParser.setXMLSchema(schema);

Setting the error handler

As in the SAXParser section, define an error handling class, CustomErrorHandler. Create a CustomErrorHandler object, and register the ErrorHandler object with the DOMParser using the setErrorHandler method.

CustomErrorHandler errorHandler = new CustomErrorHandler();
domParser.setErrorHandler(errorHandler);

We have used a SAX-based error handler for a DOM parser because most DOM parsers use a SAX parser internally.

Parsing the XML document

The DOMParser class extends the XMLParser class that provides the overloaded parse methods discussed in the previous section to parse an XML document. The preferred parse method is parse(InputSource) because the DOM parser uses an SAX parser internally and SAX parsers use an InputSource object for parsing. If another input type is specified, the input is converted to an InputSource by the SAX parser. Create an InputStream object from the example XML document, catalog. xml, and create an InputSource object from the InputStream object. Subsequently, parse the XML document using the parse(InputSource) method:

InputStream inputStream=new FileInputStream(new
File("catalog.xml"));
InputSource inputSource=new InputSource(inputStream);
domParser.parse(inputSource);

Running the Java application

The validation application DOMValidator.java is listed in the following listing with explanations:

  1. First, we declare the import statements for the classes that we need.
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import oracle.xml.parser.schema.*;
    import oracle.xml.parser.v2.*;
    import java.io.IOException;
    import java.io.InputStream;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.xml.sax.helpers.DefaultHandler;
    import org.xml.sax.InputSource;
  2. We define the Java class DOMValidator.
    public class DOMValidator {
  3. In the Java class we add a method validateXMLDocument.
    public void validateXMLDocument(InputSource input) {
    try {
  4. We create a DOMParser object and set the XML schema on the DOMParser.
     DOMParser domParser = new DOMParser();
    domParser.setValidationMode(XMLParser.SCHEMA_VALIDATION);
    XMLSchema schema=getXMLSchema();
    domParser.setXMLSchema(schema);
  5. We create a CustomErrorHandler object and set the error handler on the DOMParser. We parse the XML document and output the validation errors, if any.
    CustomErrorHandler errorHandler = new CustomErrorHandler();
    domParser.setErrorHandler(errorHandler);
    domParser.parse(input);
    if (errorHandler.hasValidationError == true) {
    System.err.println("XML Document has
    Validation Error:" + errorHandler.saxParseException.getMessage());
    } else {
    System.out.println("XML Document validates
    with XML schema");
    }
    } catch (IOException e) {
    System.err.println("IOException " + e.getMessage());
    } catch (SAXException e) {
    System.err.println("SAXException " + e.getMessage());
    }
    }
  6. We define the getXMLSchema method to create an XMLSchema object.
    public XMLSchema getXMLSchema() {
    try {
    XSDBuilder builder = new XSDBuilder();
    InputStream inputStream =
    new FileInputStream(new File("catalog.xsd"));
    InputSource inputSource = new InputSource(inputStream);
    XMLSchema schema = builder.build(inputSource);
    return schema;
    } catch (XSDException e) {
    System.err.println("XSDException " + e.getMessage());
    } catch (FileNotFoundException e) {
    System.err.println("FileNotFoundException " +
    e.getMessage());
    }
    return null;
    }
  7. We add the main method in which we create an instance of the DOMValidator class and invoke the validateXMLDocument method.
    public static void main(String[] argv) {
    try {
    InputStream inputStream =
    new FileInputStream(new File("catalog.xml"));
    InputSource inputSource=new InputSource(inputStream);
    DOMValidator validator = new DOMValidator();
    validator.validateXMLDocument(inputSource);
    } catch (FileNotFoundException e) {
    System.err.println("FileNotFoundException " +
    e.getMessage());
    }
    }
  8. Finally, we define the CustomErrorHandler inner class.
    private class CustomErrorHandler extends DefaultHandler {
    protected boolean hasValidationError = false;
    protected SAXParseException saxParseException = null;
    public void error(SAXParseException exception)
    {
    hasValidationError = true;
    saxParseException = exception;
    }
    public void fatalError(SAXParseException exception)
    {
    hasValidationError = true;
    saxParseException = exception;
    }
    public void warning(SAXParseException exception)
    {
    }
    }
    }

To demonstrate error handling, add a title element to the journal element. A title element is not valid in a journal element. Copy the DOMValidator.java application to the DOMValidator.java application in SchemaValidation project. To run the DOMValidator.java application, right-click on DOMValidator.java in Application Navigator, and select Run. A validation error gets outputted, indicating that the title element is not valid. If the title element in the journal element is removed and the DOMValidator.java application is re-run, a validation message gets outputted to indicate that the XML document is valid.

Processing XML documents with Oracle JDeveloper 11g

Summary

An XML schema defines the structure of an XML document. In this article we discussed validating an XML document with an XML schema. JDeveloper 11g provides built-in support for validating an XML document with an XML schema. JDeveloper also includes the XDK 11g through which an XML document may be validated with an XML schema in a Java application. We discussed the  SAXPaser and DOMParser classes to validate an XML document.

 

If you have read this article you may be interested to view :

 

Processing XML documents with Oracle JDeveloper 11g Create, validate, and transform XML documents with Oracle's JDeveloper IDE using this book and eBook
Published: May 2009
eBook Price: $32.99
Book Price: $54.99
See more
Select your format and quantity:

About the Author :


Deepak Vohra

Deepak Vohra is a consultant and a principal member of the NuBean.com software company. Deepak is a Sun Certified Java Programmer and Web Component Developer, and has worked in the fields of XML and Java programming and J2EE for over five years. Deepak is the co-author of the Apress book Pro XML Development with Java Technology and was the technical reviewer for the O'Reilly book WebLogic: The Definitive Guide. Deepak was also the technical reviewer for the Course Technology PTR book Ruby Programming for the Absolute Beginner, and the technical editor for the Manning Publications book Prototype and Scriptaculous in Action. Deepak is also the author of the Packt Publishing books JDBC 4.0 and Oracle JDeveloper for J2EE Development; Processing XML documents with Oracle JDeveloper 11g; EJB 3.0 Database Persistence with Oracle Fusion Middleware 11g; and Java 7 JAX-WS Web Services.

Books From Packt

 

JDBC 4.0 and Oracle JDeveloper for J2EE Development
JDBC 4.0 and Oracle JDeveloper for J2EE Development

Mastering Oracle Scheduler in Oracle 11g Databases
Mastering Oracle Scheduler in Oracle 11g Databases

SOA Cookbook
SOA Cookbook

Oracle Web Services Manager
Oracle Web Services Manager

Oracle Modernization Solutions
Oracle Modernization Solutions

SOA and WS-BPEL
SOA and WS-BPEL

Oracle SOA Suite Developer's Guide
Oracle SOA Suite Developer's Guide

PHP Oracle Web Development: Data processing, Security, Caching, XML, Web Services, and Ajax
PHP Oracle Web Development: Data processing, Security, Caching, XML, Web Services, and Ajax

 

No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
z
H
D
C
a
Y
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software