Sunday, June 21, 2015

Validate XML With Referenced XSD File Using DOM Parser

On the last post we learn how to validated a XML file against an external XML schema file. Now we try to learn how to validate a XML file against referenced or internal schema definition.

Step 1 :

Create DocumentBuilderFactory object as given below.
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); 

Step 2 :

Set DocumentBuilderFactory object as NameSpace Aware true.
     docFactory.setNamespaceAware(true);

Step 3:

Set DocumentBuilderFactory object as Validating true.
     docFactory.setValidating(true);

Until we set docFactory as NameSpaceAware it will not validate the XML file with referenced Schema if we only set the Validating as true.

Step 4:

Set Attribute on DocumentBuilderFactory.

 If schemalocation specified in the XML Document using the schemaLocation or  noNamespaceSchemaLocation attributes then use
    docFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
              "http://www.w3.org/2001/XMLSchema");


If schemalocation specified by the 'http://java.sun.com/xml/jaxp/properties/schemaSource' property then use
    docFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
              "http://www.w3.org/2001/XMLSchema");


    docFactory.setAttribute( "http://java.sun.com/xml/jaxp/properties/schemaSource", "file:test2.xsd");


Step 5:

Set ErrorHandler to DocumentBuilderFactory object. It is optional,  it is required if we try to catch different level of parsing error like warning, error, fatal error etc.

We can set this on DocumentBuilder Object like this.
      docBuilder.setErrorHandler(new DefaultErrorHandler());

Or if we want to implement our own then it looks like this.
            docBuilder.setErrorHandler(
                    new ErrorHandler() {
                        @Override
                        public void warning(SAXParseException e) throws SAXException {
                            System.out.println("WARNING: " + e.getMessage()); // do nothing
                        }

                        @Override
                        public void error(SAXParseException e) throws SAXException {
                            System.out.println("ERROR: " + e.getMessage());
                            throw e;
                        }

                        @Override
                        public void fatalError(SAXParseException e) throws SAXException {
                            System.out.println("FATAL: " + e.getMessage());
                            throw e;
                        }
                    });


Step 6 :

Now parse the XML file.
    docBuilder.parse(new File("file.xml"));

Our complete code looks like that:

package domparsing;

import com.sun.org.apache.xml.internal.utils.DefaultErrorHandler;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class DOMValidation {

    /**
     * @param args the command line arguments
     * @throws javax.xml.parsers.ParserConfigurationException
     * @throws org.xml.sax.SAXException
     * @throws java.io.IOException
     */
    public static void main(String[] args) {
        try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            docFactory.setNamespaceAware(true);
            docFactory.setValidating(true);
            /**
             * This line is required if We setValidating as true
             * but no noNamespaceSchemaLocation defined in XML file.
             */

            //docFactory.setFeature("http://apache.org/xml/features/validation/dynamic", true);
            docFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
              "http://www.w3.org/2001/XMLSchema");
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            //docBuilder.setErrorHandler(new DefaultErrorHandler());

            docBuilder.setErrorHandler(
                    new ErrorHandler() {
                        @Override
                        public void warning(SAXParseException e) throws SAXException {
                            System.out.println("WARNING: " + e.getMessage()); // do nothing
                        }

                        @Override
                        public void error(SAXParseException e) throws SAXException {
                            System.out.println("ERROR: " + e.getMessage());
                            throw e;
                        }

                        @Override
                        public void fatalError(SAXParseException e) throws SAXException {
                            System.out.println("FATAL: " + e.getMessage());
                            throw e;
                        }
                    });
            /**
             * Commented line required if we want to
             * show the output after parsing it.One is
             * for using DOM and another is one using STAX.
             */

            //TransformerFactory.newInstance().newTransformer().transform(new StreamSource("file.xml"), new StreamResult(System.out));
            //TransformerFactory.newInstance().newTransformer().transform(new DOMSource(docBuilder.parse(new File("file.xml"))),new StreamResult(System.out));
            docBuilder.parse(new File("file.xml"));
        } catch (IOException | SAXException | ParserConfigurationException | IllegalArgumentException e) {
            System.out.println("!!!!!!!!!!!!!!!Error!!!!!!!!!!!!" + e.getMessage());
        }
    }
}


XML File :

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<students  xsi:noNamespaceSchemaLocation="file.xsd"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <student id="1">
    <fname>TestFirstName</fname>
    <lname>TestLastName</lname>
    <sectionname rollno="1">A</sectionname>
  </student>
</students>




XML Schema :

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" attributeFormDefault="unqualified" elementFormDefault="qualified">
  <xs:element name="students" type="studentsType"/>
  <xs:complexType name="sectionnameType">
    <xs:simpleContent>
      <xs:extension base="xs:string">
        <xs:attribute type="xs:byte" name="rollno"/>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
  <xs:complexType name="studentType">
    <xs:sequence>
      <xs:element type="xs:string" name="fname"/>
      <xs:element type="xs:string" name="lname"/>
      <xs:element type="sectionnameType" name="sectionname"/>
    </xs:sequence>
    <xs:attribute type="xs:byte" name="id"/>
  </xs:complexType>
  <xs:complexType name="studentsType">
    <xs:sequence>
      <xs:element type="studentType" name="student"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>

No comments:

Post a Comment