如何使用JDom针对XSD架构验证XML文档

时间:2012-05-09 21:09:05

标签: java validation jdom

我正在开发一个使用JDom解析 XML 文档的应用程序。

以下是现有代码:

private Document openDocumentAtPath(File file) {

        // Create a sax builder for building the JDOM document
        SAXBuilder builder = new SAXBuilder();

        // JDOM document to be created from XML document
        Document doc = null;

        // Try to build the document
        try {

            // Get the file into a single string
            BufferedReader input =  new BufferedReader(
                new FileReader( file ) );
            String content = "";
            String line = null;
            while( ( line = input.readLine() ) != null ) {
                content += "\n" + line;
            }

            StringReader reader = new StringReader( content );
            doc = builder.build(reader);


        }// Only thrown when a XML document is not well-formed
        catch ( JDOMException e ) {
            System.out.println(this.file + " is not well-formed!");
            System.out.println("Error Message: " + e.getMessage());
        } 
        catch (IOException e) {
            System.out.println("Cannot access: " + this.file.toString());
            System.out.println("Error Message: " + e.getMessage());
        }
        return doc;
    }

现在我还要根据 XSD 验证XML。我读了API,它告诉我使用JAXP和东西,我不知道如何。

应用程序正在使用 JDom 1.1.1 ,我在网上找到的示例使用了此版本中未提供的一些类。有人可以解释如何针对XSD验证XML,尤其是对于此版本。

2 个答案:

答案 0 :(得分:4)

如何简单地从JDOM FAQ复制粘贴代码?

答案 1 :(得分:2)

或者,使用JDOM 2.0.1,并更改行:

SAXBuilder builder = new SAXBuilder();

SAXBuilder builder = new SAXBuilder(XMLReaders.XSDVALIDATING);

请参阅JDOM 2.0.1 javadoc(页面底部的示例):http://hunterhacker.github.com/jdom/jdom2/apidocs/org/jdom2/input/sax/package-summary.html

哦,我应该更新常见问题