我需要编写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或代码有什么问题吗?
答案 0 :(得分:2)
您应该使用DocumentBuilderFactory
方法使setNamespaceAware()
知道名称空间。
答案 1 :(得分:2)
您应该在构建器工厂中启用名称空间。
DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
fact.setNamespaceAware(true);
DocumentBuilder parser = fact.newDocumentBuilder();