简体   繁体   中英

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.

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 . I read the API and it tells to use JAXP and stuff and I don't know how.

The application is using JDom 1.1.1 and the examples I found online used some classes that are not available in this version. Can someone explain how to validate an XML against an XSD, especially for this version.

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

Or, use JDOM 2.0.1, and change the line:

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

Oh, and I should update the FAQs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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