简体   繁体   English

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

[英]How to validate an XML document against an XSD schema using JDom

I am working on an application that used JDom for parsing XML documents. 我正在使用JDom解析XML文档的应用程序上工作。

Following is the existing code: 以下是现有代码:

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;
    }

Now I also want to validate the XML against an XSD . 现在,我还想针对XSD验证XML。 I read the API and it tells to use JAXP and stuff and I don't know how. 我阅读了API ,它告诉您使用JAXP和其他东西,但我不知道如何使用。

The application is using JDom 1.1.1 and the examples I found online used some classes that are not available in this version. 该应用程序使用的是JDom 1.1.1 ,我在网上找到的示例使用了该版本中不可用的一些类。 Can someone explain how to validate an XML against an XSD, especially for this version. 有人可以解释如何针对XSD验证XML,尤其是针对该版本的XML。

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

Or, use JDOM 2.0.1, and change the line: 或者,使用JDOM 2.0.1,并更改以下行:

SAXBuilder builder = new SAXBuilder();

to be 成为

SAXBuilder builder = new SAXBuilder(XMLReaders.XSDVALIDATING);

See the JDOM 2.0.1 javadoc (examples at bottom of page): http://hunterhacker.github.com/jdom/jdom2/apidocs/org/jdom2/input/sax/package-summary.html 请参阅JDOM 2.0.1 Javadoc(示例在页面底部): http : //hunterhacker.github.com/jdom/jdom2/apidocs/org/jdom2/input/sax/package-summary.html

Oh, and I should update the FAQs 哦,我应该更新常见问题解答

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM