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.
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
精彩评论