1

我需要编写 Java 代码来根据模式验证 XML。由于某种我不明白的原因,验证失败,出现以下异常:

org.xml.sax.SAXParseException; cvc-elt.1: Cannot find the declaration of element 'root'

架构:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema elementFormDefault="qualified"
    targetNamespace="http://www.example.com"
    xmlns="http://www.example.com"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="root" type="rootType"/>
    <xs:simpleType name="rootType">
        <xs:restriction base="xs:integer"/>
    </xs:simpleType>
</xs:schema>

XML:

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns="http://www.example.com">1</root>

Java代码:

try (InputStream xmlStream = Main.class.getClassLoader().getResourceAsStream("a.xml");
        InputStream xsdStream = Main.class.getClassLoader().getResourceAsStream("a.xsd")) {
    DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document document = parser.parse(xmlStream);
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    StreamSource schemaFile = new StreamSource(xsdStream);
    Schema schema = factory.newSchema(schemaFile);
    Validator validator = schema.newValidator();
    validator.validate(new DOMSource(document));
}

如果我删除对命名空间“ http://www.example.com ”的所有引用,则验证成功。架构、XML 或代码有什么问题吗?

4

2 回答 2

3

您应该在构建器工厂中启用命名空间。

    DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
    fact.setNamespaceAware(true);
    DocumentBuilder parser = fact.newDocumentBuilder();
于 2019-04-30T13:48:11.627 回答
2

您应该使用该方法使DocumentBuilderFactory命名空间感知。setNamespaceAware()

于 2019-04-30T13:15:12.973 回答