XML JDOM dtd validation saxbuilder

XSD example

The XML and the DTD file are in the same classpath folder.

DTD

{% highlight xml %}
<?xml version=“1.0” encoding=“UTF-8” ?>
<!ELEMENT orders (order*)>
<!ELEMENT order (customer+,products?) >
<!ATTLIST order number CDATA #REQUIRED>

<!ELEMENT customer (name?)>
<!ATTLIST customer number CDATA #REQUIRED>
<!ELEMENT name (#PCDATA)>

<!ELEMENT products (product)*>

<!ELEMENT product EMPTY>
<!ATTLIST product name CDATA #REQUIRED>
<!ATTLIST product quantity CDATA #REQUIRED>
<!ATTLIST product price CDATA #REQUIRED>
{% endhighlight %}

XML

{% highlight xml %}
<?xml version=“1.0” encoding=“UTF-8”?>



abc

{% endhighlight %}

Java code using validation

{% highlight java %}
package de.laliluna.example;

import java.io.IOException;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class Example {
public static void main(String[] args) {
// true activates validation
SAXBuilder saxBuilder = new SAXBuilder(true);
try {
Document document = saxBuilder.build(Example.class
.getResource(“/order.xml”));
XMLOutputter outputter = new XMLOutputter(
Format.getPrettyFormat());
outputter.output(document, System.out);
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
{% endhighlight %}