Java 获取XSD验证错误上的父元素

Java 获取XSD验证错误上的父元素,java,xml,sax,saxparser,Java,Xml,Sax,Saxparser,我有以下带有unit&measure子元素的xml <Depth> <measure>1.00</measure> <unit>in</unit> <Depth> <Width> <measure>1.00</measure> <unit>in</unit> </Width> <vendorPackHeight>

我有以下带有unit&measure子元素的xml

<Depth>
    <measure>1.00</measure>
    <unit>in</unit>
<Depth>
<Width>
    <measure>1.00</measure>
    <unit>in</unit>
</Width>
<vendorPackHeight>
    <measure>1.00</measure>
    <unit>in</unit>
</vendorPackHeight>
<Weight>
    <measure>7.00</measure>
    <unit>LBS</unit> //invalid expected value is lb
</Weight> 

1
在里面
1
在里面
1
在里面
7
LBS//无效的预期值为lb
当单位或度量值子元素的XSD验证失败且出现类似cvc enumeration valid的错误时(当度量值不是来自一组枚举值时),或单位值失败且cvc数据类型有效时。1.2.1当数据类型不匹配时,如何获取父元素?在上面的xml中,它是权重


在SAXParseException中,我得到了发生错误的行号。是否可以从行号中获取元素,然后获取其父元素

我认为在JavaAPI中没有标准的方法来实现这一点。不过,有些库确实允许您查看它当前所在的元素。例如,在ApacheXerces实现中,它支持通过

getProperty(“http://apache.org/xml/properties/dom/current-element-node“”

在其网站上查看有关该物业的文档:


默认情况下,由JDK提供,但也可以作为第三方库导入到项目中。如果您必须使用它才能正确运行应用程序,我建议您添加它。下面是一些示例代码,用于将XML文档验证为XSD并获取当前节点

import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.apache.xerces.impl.Constants;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXParseException;

public class XSDTest {

    public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {

        // our XSD, which defines 1 node  <TheNode> which must have decimal text content 
        byte [] schemaData = ("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
                + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">"
                    + "<xs:simpleType name=\"theNodeType\">"
                        + "<xs:restriction base=\"xs:decimal\"/>"
                    + "</xs:simpleType>"
                    + "<xs:element name=\"TheNode\" type=\"theNodeType\"/>"
                + "</xs:schema>").getBytes();
        // our invalid xml
        byte [] xmlData = "<TheNode>123NotADecimal</TheNode>".getBytes();

        // parse schema
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Source schemaSource = new StreamSource(new ByteArrayInputStream(schemaData));
        Schema schema = schemaFactory.newSchema(schemaSource);

        // build our document, must use document builder to enable xerces parser properties for DOM
        // Also must be a xerces implementation of the DBF, should be enabled by default in a standard java project but just to be verbose about it
        // pass in the full name of the DBF impl
        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));


        // configure our validator and parse the document.
        Validator validator = schema.newValidator();
        validator.setErrorHandler(new MyErrorHandler(validator));
        validator.validate(new DOMSource(doc.getDocumentElement()));
    }

    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-node"
            // see https://xerces.apache.org/xerces2-j/properties.html#dom.current-element-node
            return (Node)xsdValidator.getProperty(Constants.XERCES_PROPERTY_PREFIX + Constants.CURRENT_ELEMENT_NODE_PROPERTY);
        }
    }

}

如果切换到Saxon作为模式验证器,您将能够找到这些信息

当您使用Saxon验证内存中的树时,ValidationFailure对象包含对验证失败的实际节点的引用(显然,您可以从那里导航到父节点)


使用Saxon验证SAX流时,ValidationFailure对象包含一个路径,该路径是一个结构化对象,包含有关发生故障的节点及其每个祖先的信息。每个祖先的可用信息包括节点种类、节点名称和同级位置。

我最终使用元素逐个生成XML,并在每个步骤中进行验证,以确认子元素是否有效。如果有更好的解决方案,这将是gr8。这意味着XML对于模式无效。是否附加用于查看架构内容的链接?
Error on node: [TheNode: null]
cvc-datatype-valid.1.2.1: '123NotADecimal' is not a valid value for 'decimal'.
Error on node: [TheNode: null]
cvc-type.3.1.3: The value '123NotADecimal' of element 'TheNode' is not valid.