views:

56

answers:

1

I want to create a SAXParser which validates, but it seems the only way is either to create an XMLReader and use setErrorHandler() or let the ContentHandler in SAXParser.parse() also implement ErrorHandler.

Am I missing something? All I want to do is create a validating SAXParser like this:

private SAXParser createParser(final boolean validateXML) throws ParserConfigurationException, SAXException {
  final SAXParserFactory factory = SAXParserFactory.newInstance();

  factory.setNamespaceAware(true);
  factory.setValidating(validateXML);
  factory.setFeature("http://apache.org/xml/features/validation/schema", validateXML);

  SAXParser parser = factory.newSAXParser();

  Assert.assertNotNull("Checking parser exists", parser);
  Assert.assertEquals("Checking validation", validateXML, parser.isValidating());
  Assert.assertTrue("Checking namespace awareness", parser.isNamespaceAware());
  return parser;
}

I'm using Xerces 2.9.1

Thanks for any hints!

Eric

A: 

Maybe I misunderstand, but is this a solution for you? --> Xerces2 XSD Validation with SAXParser

Jeroen Rosenberg
Unfortunately no, since from my experience the SAXParser itself doesn't validate. You have to parse an XML document and add an ErrorHandler to discover whether the XML is valid or invalid. So, even though the SAXParser itself tells you it's validating, it actually isn't, it's only the ContentHandler/ErrorHandler that makes the difference.At least that's what I experienced... It would be nice to be proven wrong :-)