Jdom XSD Schema validation

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

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

…..
{% 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);
// 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();
}
}
}
{% endhighlight %}