我现在使用的是Java8,目前我正在尝试使用验证器(javax.xml.validation.Validator)来验证XSD schema。我的目标是能够检索包含验证错误的元素的节点。
在我的代码中,我使用了一个应用于我的验证器的ErrorHandler。此外,我添加了一个getCurrentNode()方法,它应该返回错误节点(validator.getProperty("http://apache.org/xml/properties/dom/current-element-node")。在我的例子中,getProperty(“-”)方法返回null而不是node对象。我不明白为什么?我希望不是因为我的一个components...Can的版本问题,比我更有知识的人知道出了什么问题吗?
我从以下响应中提取了代码:Get parent element on XSD validation error。
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;
}
}发布于 2021-05-12 18:11:50
解决方法:为了能够使用节点,您必须使用Document对象,如果您直接验证文件而不使用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));https://stackoverflow.com/questions/67500546
复制相似问题