Java HTML / XML How to - Validate XML with XML Schema








Question

We would like to know how to validate XML with XML Schema.

Answer

import java.io.File;
//  www . j a  v  a 2 s .  c  om
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Main {

  public static void main(String[] args) throws Exception {
    SchemaFactory sf = SchemaFactory
        .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(new File("data.xsd"));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setSchema(schema);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.parse(new File("data.xml"));

    Element result = document.getElementById("abc");
    System.out.println(result);
  }

}

XML Input (data.xsd)

<?xml version="1.0" encoding="UTF-8"?>
<schema 
    xmlns="http://www.w3.org/2001/XMLSchema" 
    targetNamespace="http://www.example.org/schema" 
    xmlns:tns="http://www.example.org/schema" 
    elementFormDefault="qualified">

    <element name="foo">
        <complexType>
            <sequence>
                <element ref="tns:bar" maxOccurs="unbounded"/>
            </sequence>
        </complexType>
    </element>

    <element name="bar">
        <complexType>
            <attribute name="id" type="ID"/>
        </complexType>
    </element>

</schema>

XML Input (input.xml)

<?xml version="1.0" encoding="UTF-8"?>
<foo xmlns="http://www.example.org/schema">
    <bar id="ABCD"/>
    <bar id="EFGH"/>
    <bar id="IJK"/>
</foo>