有没有办法在Java中验证内存中的XML DOM树?

时间:2009-11-11 16:00:47

标签: java xml

我正在使用DocumentBuilderFactory和w3c.org的Document类创建XML文档。我想在将结果写入文件之前针对XSD验证结果结构。 我知道我可以将DocumentBuilderFactory设置为在创建时进行验证,但我不愿意,因为我正在使用它做其他事情。

感谢。

1 个答案:

答案 0 :(得分:3)

看起来javax.xml.validation包具有您想要的功能。如果您已将Document加载到名为 document 的变量中,那么应该这样做:

// 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!
}

从这个页面:

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

相关问题