XML JDOM dtd validation saxbuilder
Quick notes on activating DTD validation with schemas.
XSD example
The XML and the DTD file are in the same classpath folder.
DTD
<?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>
XML
<?xml version="1.0" encoding="UTF-8"?> <orders xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="order.xsd"> <order number="123"> <customer number="999"> <name>abc</name> </customer> <products> <product name="abc" price="1" quantity="2" /> <product name="umbrella" price="22.5" quantity="1"/> </products> </order> </orders>
Java code using validation
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();
}
}
}