Tuesday, August 28, 2007

Dom4j Schema Validation

XML:

<?xml version="1.0"?>
<reportingConfig xmlns="http://services.bamnetworks.com/reporting/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://services.bamnetworks.com/reporting/ reporting-config.xsd"
>
...
</reportingConfig>


XSD:

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://services.bamnetworks.com/reporting/"
xmlns:tns="http://services.bamnetworks.com/reporting/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified"
>
...
</xsd:schema>


Java code:


import org.dom4j.io.SAXReader;
import org.dom4j.Document;
....

SAXReader reader = new SAXReader(true);

reader.setFeature("http://apache.org/xml/features/validation/schema", true);

// set the validation feature to true to report validation errors
reader.setFeature("http://xml.org/sax/features/validation", true);

// set the validation/schema feature to true to report validation errors against a schema
reader.setFeature("http://apache.org/xml/features/validation/schema", true);

// set the validation/schema-full-checking feature to true to enable full schema, grammar-constraint checking
reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);

Document document = reader.read(reportingConfigURL);

No comments: