0

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.

Ankit
  • 6,772
  • 11
  • 48
  • 84

2 Answers2

4

How about simply copy-pasting code from the JDOM FAQ?

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
2

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

rolfl
  • 17,539
  • 7
  • 42
  • 76
  • does JDOM2 support XSD 1.1? (specifically `xs:assert`) ? I googled but still can't figure out the answer – ycomp Nov 20 '15 at 18:22
  • @ycomp - JDOM does not do the actual parsing, it uses the underlying parser (typically xerces, or the version of xerces packaged with Java) to do that. JDOM just does the in-memory model. Xerces does support XSD1.1 I believe, see: http://xerces.apache.org/xerces2-j/xml-schema.html#supported-schema-1.1-features – rolfl Nov 20 '15 at 19:06