Jdom XSD Schema validation
Quick notes on XSD schema validation with JDOM
I had some problems with schema validation using JDom. As it was slightly tricky to find a solution in the Internet, I created this quick post.
The XML and the XSD are in the same classpath folder.
XSD extract
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="orders">
<xs:complexType>
<xs:sequence>
<xs:element ref="order" maxOccurs="unbounded"
minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
.....
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);
// this line activates schema validation
saxBuilder.setFeature(
"http://apache.org/xml/features/validation/schema", true);
try {
Document document = saxBuilder.build(Example.class
.getResource("/order-xsd.xml"));
XMLOutputter outputter = new XMLOutputter(
Format.getPrettyFormat());
outputter.output(document, System.out);
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}