How can I get more information on an invalid DOM element through the Validator?

前端 未结 2 772
醉话见心
醉话见心 2021-01-13 03:27

I am validating an in-memory DOM object using the javax.xml.validation.Validator class against an XSD schema. I am getting a SAXParseException bein

相关标签:
2条回答
  • 2021-01-13 04:23

    If you are using Xerces (the Sun JDK default), you can get the element that failed validation through the http://apache.org/xml/properties/dom/current-element-node property:

    ...
    catch (SAXParseException e)
    {
        Element curElement = (Element)validator.getProperty("http://apache.org/xml/properties/dom/current-element-node");
    
        System.out.println("Validation error: " + e.getMessage());
        System.out.println("Element: " + curElement);
    }   
    

    Example:

    String xml = "<root xmlns=\"http://www.myschema.org\">\n" +
                 "<text>This is text</text>\n" +
                 "<number>32</number>\n" +
                 "<number>abc</number>\n" +
                 "</root>";
    
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document doc = dbf.newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));
    Schema schema = getSchema(getClass().getResource("myschema.xsd"));
    
    Validator validator = schema.newValidator();
    try
    {
        validator.validate(new DOMSource(doc));
    }
    catch (SAXParseException e)
    {
        Element curElement = (Element)validator.getProperty("http://apache.org/xml/properties/dom/current-element-node");
    
        System.out.println("Validation error: " + e.getMessage());
        System.out.println(curElement.getLocalName() + ": " + curElement.getTextContent());
    
        //Use curElement.getParentNode() or whatever you need here
    }         
    

    If you need to get line/column numbers from the DOM, this answer has a solution to that problem.

    0 讨论(0)
  • 2021-01-13 04:28

    SaxParseException exposes the SystemId and PublicId. Does that not give you enough information?

    0 讨论(0)
提交回复
热议问题