tags:

views:

38

answers:

2

So say I have an xml file that looks like this:

<foo>
 <bar></bar>
 <bar></bar>
 <bar></bar>
 ...
 <bar></bar>
</foo>

My goal is to validate each bar tag against a DTD. For simplicity, lets say that for each bar node that passes validation against the DTD the program outputs "true" and each bar node that fails it outputs "fail"

Using a SAX parser how would i implement this?

Thanks!

A: 

Tricky, because a (validating) standard XML parser will stop on the first validation error. The eclipse XML editor is different, it shows all validation errors, but it's not easy it all to extract it and use it outside the eclipse framework...

Try this: parse the whole document with a not-validating SAX Parser and feed each bar element to a second validating parser. You'll need a derived dtd for the second parser, because it will see a root element named bar. This should give validation results for the bar elements.

Andreas_D
+1  A: 

Use a validating SAX parser and be sure to set an org.xml.sax.ErrorHandler on the org.xml.sax.XMLReader. ErrorHandler is an interface you can implement with 3 methods:

  • warning(SAXParseException exception)
  • error(SAXParseException exception)
  • fatalError(SAXParseException exception)

If your implementation of ErrorHandler throws an Exception from these methods parsing will stop. On the other hand you can catch the SAXParseException store it in a collection, and simply return from the ErrorHandler methods and parsing will continue. Once parsing is complete you can check your implementation of ErrorHandler for the stored exceptions.

SAXParseException contains useful information such as column/line number of where the error occurred.

Blaise Doughan
+1 - great idea, I'll keep that in mind!
Andreas_D
I used a variation of this, thanks
peterJ