Java - XML Validation with Schema

In this article, let us see how to validate XML file against the XML Schema.

Let us take a simple XML Schema file as follows,

XML Schema

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
        <xs:element name="Person">
                <xs:complexType>
                        <xs:attribute name="Name" type="xs:string"/>
                        <xs:attribute name="Country" type="xs:string"/>
                </xs:complexType>
        </xs:element>
</xs:schema>

Lets us construct the XML file which we will use to validate with the Schema.

Sample XML

<?xml version="1.0" encoding="UTF-8"?>
<Person Name="TechDive.in" Country="India" />

The below Java class performs the following,
1. Loads the XML Schema File (conf/input.xsd)
2. Loads the XML File (conf/input.xml)
3. Validates the XML File with the XML Schema.

XMLValidator Class

package in.techdive.xml.example;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringReader;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;

/**
 * Class used to perform XML Validation against the XML Schema
 */

public class XMLValidator
{
        /**
         * Method used to Read XML File as String
         *
         * @param xmlFilePath XML File Path
         * @return XML String
         */

        public static String readXMLFile(String xmlFilePath)
        {
                FileInputStream fis;
                StringBuffer sb = null;
                try
                {
                        fis = new FileInputStream(xmlFilePath);
                        DataInputStream in = new DataInputStream(fis);
                        sb = new StringBuffer();
                        while (in.available() != 0)
                        {
                                String line = in.readLine();
                                sb.append(line + "\n");
                        }
                        return sb.toString();
                }
                catch (FileNotFoundException e)
                {
                        e.printStackTrace();
                }
                catch (IOException e)
                {
                        e.printStackTrace();
                }

                return null;
        }

        /**
         * Method used to get XML Document form XML String
         */

        public static Document getXMLDocument(String xmlString) throws Exception
        {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document document = builder.parse(new InputSource(new StringReader(
                                xmlString)));
                return document;
        }

        /**
         * Validate the XML Node with the XSD Schema
         */

        public static void validateXML(String xmlSchemaPath, Node xmlNode)
                        throws Exception
        {
                SchemaFactory factory = SchemaFactory
                                .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
                StreamSource ss = new StreamSource(xmlSchemaPath);
                Schema xmlSchema = factory.newSchema(ss);
                Validator v = xmlSchema.newValidator();
                v.validate(new DOMSource(xmlNode));
        }

        /**
         * Method does the following operations,
         *      1. Loads the XML String from the File named "conf/input.xml"
         *      2. Loads the XML Schema from the File named "conf/input.xsd"
         *      3. Validates the XML data with the XML schema
         */

        public static void main(String[] args) throws Exception
        {
                String xmlFileName = "conf/input.xml";
                String xmlSchemaFile = "conf/input.xsd";

                String xmlString = readXMLFile(xmlFileName);
                // System.out.println("XML String = " + xmlString);
                Document doc = getXMLDocument(xmlString);

                Element node = doc.getDocumentElement();

                try
                {
                        validateXML(xmlSchemaFile, node);
                        System.out.println("Result: " + xmlFileName + " is a valid XML");
                }
                catch (Exception e)
                {
                        // e.printStackTrace();
                        System.err
                                        .println("Error in validating the XML file against the XML Schema");
                }
        }
}

Output :

Result: conf/input.xml is a valid XML
Technology: 

Search