0

我正在开发一个使用 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,尤其是对于这个版本。

4

2 回答 2

4

JDOM FAQ中简单地复制粘贴代码怎么样?

于 2012-05-09T21:13:31.787 回答
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

哦,我应该更新常见问题解答

于 2012-05-09T21:32:48.590 回答