public class ValidatorErrorHandler implements ErrorHandler { private Validator validator; public ValidatorErrorHandler(Validator v) { validator = v; } ... public void error(SAXParseException spe) throws SAXException { Node node = null; try { node = (Node) validator.getProperty( "http://apache.org/xml/properties/dom/current-element-node"); } catch (SAXException se) {} ... }
... Validator validator = schema.newValidator(); validator.setErrorHandler(new MyErrorHandler(validator)); ... public class MyErrorHandler implements ErrorHandler { private Validator validator; public AnnotatingErrorHandler(Validator v) { super(); validator = v; } @Override public void error(SAXParseException e) throws SAXException { try { element = (Element)validator.getProperty("http://apache.org/xml/properties/dom/current-element-node"); } catch (SAXNotRecognizedException e) { log(Level.SEVERE, "Xerxes 2 XML parser is required", saxnre); } catch (SAXNotSupportedException e) { ; // shouldn't happen in this context } ... // do stuff } ... }
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 }
try { String ppn = saxPropertyPrefix + pn; Object pv = v.getProperty(ppn); assert pv != null; sb.append("SAX property: {" + ppn + "}: " + pv.toString() + "\n"); try { String ppn = jaxpPropertyPrefix + pn; Object pv = v.getProperty(ppn); assert pv != null; sb.append("JAXP property: {" + ppn + "}: " + pv.toString() + "\n"); try { String ppn = xercesPropertyPrefix + pn; Object pv = v.getProperty(ppn); assert pv != null; sb.append("XERCES property: {" + ppn + "}: " + pv.toString() + "\n");
return (Node)xsdValidator.getProperty(Constants.XERCES_PROPERTY_PREFIX + Constants.CURRENT_ELEMENT_NODE_PROPERTY);