0

嗨,我正在使用 Java 8,目前我正在尝试使用验证器 (javax.xml.validation.Validator) 使用 XSD 模式验证 XML。我的目标是能够检索包含验证错误的元素的节点。

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

我从以下响应中获取了代码: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;
    }
}
4

1 回答 1

0

已解决:为了能够使用节点,您必须使用 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));
于 2021-05-12T10:11:49.807 回答