【问题标题】:Is there a way to validate an in memory XML DOM Tree in Java?有没有办法在 Java 中验证内存中的 XML DOM 树?
【发布时间】:2009-11-11 16:00:46
【问题描述】:

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

谢谢。

【问题讨论】:

    标签: java xml


    【解决方案1】:

    看起来 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

    【讨论】:

    • 尝试实现此功能时,我的编译器无法解析 XMLConstants.W3C_XML_SCHEMA_NS_URI。我正在使用 java 1.6,文档说它应该在那里,但我没有将它视为 javax.xml.XMLConstants 类的一部分。想法?
    • 我能想到的就是确保您正在导入 javax.xml.XMLConstants。我的 IDE 建议使用其他 XMLConstants,但它们不起作用。
    • 我做到了。它只提供了另一种选择,而且绝对不是正确的选择。我只是用文档提供的 url 替换了常量。
    猜你喜欢
    • 2020-09-29
    • 2010-11-26
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 1970-01-01
    相关资源
    最近更新 更多