Java XML – JDOM2 – SAXBuilder DTD Validating

In this tutorial we look at how to use SAXBuilder to create a JDOM2 Document such that the SAXBuilder validates the XML using the DTD before creating the JDOM2 document. If you are looking for a way to create JDOM2 Document using the SAXBuilder but without any validation then this tutorial explains just that.

We explain the validation using two XML document. The first XML is invalid and therefore fails the validation step. The second XML is valid.

package com.studytrails.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;

public class JdomUsingSAXBuilderDtdValidating {
	private static String file1 = "tomcat-web-dtd-bad.xml";
	private static String file2 = "tomcat-web-dtd.xml";

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

		 SAXBuilder builder = new SAXBuilder(XMLReaders.DTDVALIDATING);
		 Document jdomDocValidatedFalse = File(file1));
		// throws an error since the XML does not validate. We correct it and
		// then run this again. comment the lines above and run this again.

		SAXBuilder builder2 = new SAXBuilder(XMLReaders.DTDVALIDATING);
		Document jdomDocValidatedTrue = File(file2));

		System.out.println(jdomDocValidatedTrue.hasRootElement()); // prints true
		DocType docType = jdomDocValidatedTrue.getDocType();

		// prints -//Sun Microsystems, Inc.//DTD Web Application 2.3//EN
		// prints


1 thought on “Java XML – JDOM2 – SAXBuilder DTD Validating”

Leave a Comment