How to validate xml against xsd and get *ALL* errors?

30,490

Between Validator validator = schema.newValidator(); and StreamSource xmlFile = new StreamSource(xml); add this fragment:

  final List<SAXParseException> exceptions = new LinkedList<SAXParseException>();
  validator.setErrorHandler(new ErrorHandler()
  {
    @Override
    public void warning(SAXParseException exception) throws SAXException
    {
      exceptions.add(exception);
    }

    @Override
    public void fatalError(SAXParseException exception) throws SAXException
    {
      exceptions.add(exception);
    }

    @Override
    public void error(SAXParseException exception) throws SAXException
    {
      exceptions.add(exception);
    }
  });

This way, after validate() you'll get full list of exceptions, but if one fatal error occurs, the parsing stops...

EDIT: the JavaDoc says: The application must assume that the document is unusable after the parser has invoked this method, and should continue (if at all) only for the sake of collecting additional error messages: in fact, SAX parsers are free to stop reporting any other events once this method has been invoked. So fatalError() may or may not cause the parsing to stop.

Share:
30,490
marioosh
Author by

marioosh

mostly Java programmer, Linux, Node.js and JavaScript technologies enthusiast...

Updated on September 23, 2021

Comments

  • marioosh
    marioosh over 2 years

    I have a standard code like below to validate xml against xsd, but it throw exception on first error and stops. How to validate xml, but continue on the first and next errors and get them all at the end ? Is it even possible ?

    public static void validate(File xml, InputStream xsd) {
        try {
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = factory.newSchema(new StreamSource(xsd));
            Validator validator = schema.newValidator();
            StreamSource xmlFile = new StreamSource(xml);
            validator.validate(xmlFile);
    
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
  • Dred
    Dred over 4 years
    It stops either fatal or simple error happen. Any other variants to collect every errors?
  • tigu
    tigu over 3 years
    @Dred it does not stop on all simple errors. I tested it and it finds 27 errors in one of my xmls. By the way: how can I get the information, which entity in my xml produced the error? I found exception.getLineNumber() but line number is not very useful in XML as it could also be all in one line.