Validate XML against DTD using JDom

A Document Type Definition (DTD) defines which elements and attributes you can use inside an XML document. Typically this DTD document is specified inside the XML document. In this example we explain haw you can validatie an XML document against a DTD using JDom.

Document Type Definition (DTD)

Here is the DTD schema example.dtd. We define a root courses element, which can have multiple course elements. This course element has a name and price element and an id attribute which is required. That’s it, any other elements defined in the XML will be invalid.

<?xml version="1.0" encoding="utf-8"?>
<!ELEMENT courses (course*)>
<!ELEMENT course (name, price)>
<!ATTLIST course id CDATA #REQUIRED>
<!ELEMENT name (#PCDATA)>
<!ELEMENT price (#PCDATA)>

This valid.xml file – as the name suggests – validates successfully against the previous example.dtd DTD file. We will use this XML document for the example.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE courses PUBLIC
        "-//JDOM//DTD validation 1.0//EN"
        "example.dtd">
<courses>
    <course id="1">
        <name>Reading XML Document using JDom</name>
        <price>0.0</price>
    </course>
    <course id="2">
        <name>Getting Started with JDom</name>
        <price>0.0</price>
    </course>
    <course id="3">
        <name>
            <![CDATA[
               characters & ? $ ^ with markup
            ]]>
        </name>
        <price>12.0</price>
    </course>
</courses>

JDom DTD Validation

We start by getting the XML document. Next, we create a SAXBuilder and pass the XMLReaders.DTDVALIDATING instance. This enables the DTD validation of the XML document. When we invoke the SAXBuilder#build() method, the XML document is validated against the DTD schema, which is included in the XML file. If the XML file is invalid, a JDOMParseException is thrown.

package com.memorynotfound.xml.jdom;

import org.jdom2.DocType;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.input.sax.XMLReaders;

import java.io.IOException;
import java.io.InputStream;

public class ValidateXmlDtdJdom {

    public static void main(String... args) throws JDOMException, IOException {

        // read file from classpath
        InputStream valid = ValidateXmlDtdJdom.class.getResourceAsStream("/valid.xml");

        // create builder
        SAXBuilder builder = new SAXBuilder(XMLReaders.DTDVALIDATING);
        Document validDocument = builder.build(valid);

        // print metadata doc type
        DocType docType = validDocument.getDocType();
        System.out.println("Public ID: " + docType.getPublicID());
        System.out.println("System ID: " + docType.getSystemID());
    }
}

When the previous code is run, it prints the following output to the console.

Public ID: -//JDOM//DTD validation 1.0//EN
System ID: example.dtd

References

Download

You may also like...