Java-XSD验证器:获取包含验证错误的元素的节点



Hie,我在Java 8中工作,目前我正在尝试使用验证器(javax.XML.validation.validator(使用XSD架构验证XML。我的目标是能够检索包含验证错误的元素的节点。

在我的代码中,我使用了一个应用于Validator的ErrorHandler。此外,我添加了一个getCurrentNode((方法,该方法应该返回错误节点(validator.getProperty("http://apache.org/xml/properties/dom/current-element-node"(。在我的例子中,getProperty("---&"(方法返回null而不是Node Object。我不明白为什么?我希望这不是因为我的一个组件的版本问题。。。比我更有见识的人能理解出了什么问题吗?

我从以下响应中获取了代码:获取XSD验证错误的父元素。

public static void validateXMLSchema(URL xsd, String xml) throws SAXException, IOException {
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(xsd);
Validator validator = schema.newValidator();
validator.setErrorHandler(new MyErrorHandler(validator));

StreamSource ssXmlPath = new StreamSource(xml); //xml is a String represanting the path file
validator.validate(ssXmlPath);
}
private static class MyErrorHandler implements ErrorHandler {
private final Validator xsdValidator;
public MyErrorHandler(Validator xsdValidator) {
this.xsdValidator = xsdValidator;
}
@Override
public void warning(SAXParseException exception) throws SAXException {
System.out.println("Warning on node: " + getCurrentNode());
System.out.println(exception.getLocalizedMessage());
}
@Override
public void error(SAXParseException exception) throws SAXException {
System.out.println("Error on node: " + getCurrentNode());
System.out.println(exception.getLocalizedMessage());
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
System.out.println("Fatal on node: " + getCurrentNode());
System.out.println(exception.getLocalizedMessage());
}

private Node getCurrentNode() throws SAXNotRecognizedException, SAXNotSupportedException {
// get prop "http://apache.org/xml/properties/dom/current-element-nodeb"
// see https://xerces.apache.org/xerces2-j/properties.html#dom.current-element-node
Node node = (Node)xsdValidator.getProperty(Constants.XERCES_PROPERTY_PREFIX + Constants.CURRENT_ELEMENT_NODE_PROPERTY);
System.out.println(node.getLocalName() + ": " + node.getTextContent());
return node;
}
}

已解决:要使用节点,必须使用Document Object,如果在没有Document的情况下直接验证文件,则没有DOM构造,Xerces也找不到任何节点。

我必须有这样的东西:

DocumentBuilderFactory dbf
DocumentBuilderFactory.newInstance(org.apache.xerces.jaxp.DocumentBuilderFactoryImpl.class.getName(), XSDTest.class.getClassLoader());
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().parse(new ByteArrayInputStream(xmlData));

最新更新