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

前端 未结 2 771
醉话见心
醉话见心 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 = "\n" +
                 "This is text\n" +
                 "32\n" +
                 "abc\n" +
                 "";
    
    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.

提交回复
热议问题