tags:

views:

38

answers:

1

I'm creating an XML document using DocumentBuilderFactory and w3c.org's Document class. I want to validate the resulting structure against an XSD before writing it out to a file. I know that I can set the DocumentBuilderFactory to validate as it is being created but I would prefer not to as I am doing other things with it.

Thanks.

+2  A: 

It looks as though the javax.xml.validation package has the functionality you want. If you have your Document loaded into a variable named document already, this ought to do the trick:

// create a SchemaFactory capable of understanding WXS schemas
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

// load a WXS schema, represented by a Schema instance
Source schemaFile = new StreamSource(new File("mySchema.xsd"));
Schema schema = factory.newSchema(schemaFile);

// create a Validator instance, which can be used to validate an instance document
Validator validator = schema.newValidator();

// validate the DOM tree
try {
    validator.validate(new DOMSource(document));
} catch (SAXException e) {
    // instance document is invalid!
}

From this page:

http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/validation/package-summary.html

Sean McMains
When trying to implement this, my compiler is unable to resolve XMLConstants.W3C_XML_SCHEMA_NS_URI. I am using java 1.6 and the documentation says it should be there, but I'm not seeing it as part of the javax.xml.XMLConstants class. Thoughts?
Casey
All I can think of is to make sure you're importing javax.xml.XMLConstants. There are other XMLConstants that my IDE suggested, but they don't work.
Sean McMains
I did. There's only one other option it gives and it definitely isn't the right one. I just replaced the constant with the url the documentation gives.
Casey