如果使用Xerces(默认为Sun JDK),则可以通过http://apache.org/xml/properties/dom/current-
element-node属性获取未通过验证的元素:
...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);}例:
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}


