我有以下 XML 文件:
<?xml version="1.0"?>
<!DOCTYPE library SYSTEM "library.dtd">
<library
xmlns="http://example.com/a"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://example.com library.xsd"
name=".NET Developer's Library">
<book>
<category>computerss</category>
<title>Programming Microsoft .NET</title>
<author>Jeff Prosise</author>
<isbn>0-7356-1376-1</isbn>
</book>
<book>
<category>computer</category>
<title>Microsoft .NET for Programmers</title>
<author>Fergal Grimes</author>
<isbn>1-930110-19-7</isbn>
</book>
</library>
以及以下 Java 代码:
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
SchemaFactory sf = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
docBuilderFactory.setSchema(sf.newSchema(new File("library.xsd")));
docBuilderFactory.setNamespaceAware(true);
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
docBuilder.parse(new FileInputStream("data.xml"));
它会产生以下错误:
[错误]:7:33: cvc-elt.1: 找不到元素“library”的声明。
如果我删除 XML 文件中的 XSD 声明,一切都会正常...
任何内部都高度赞赏。谢谢。
这是架构:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="library">
<xs:complexType>
<xs:sequence>
<xs:element ref="book" maxOccurs="unbounded"/>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="optional"/>
</xs:complexType>
</xs:element>
<xs:element name="book">
<xs:complexType>
<xs:sequence>
<xs:element ref="category"/>
<xs:element ref="title"/>
<xs:element ref="author"/>
<xs:element ref="isbn"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="category">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="computer" />
<xs:enumeration value="poetry" />
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="title" type="xs:string"/>
<xs:element name="author" type="xs:string"/>
<xs:element name="isbn" type="xs:string"/>
</xs:schema>
最佳答案
您的 XML 包含对命名空间 (xmlns="http://example.com/a") 的引用,该引用与您的架构中的不同。您是否尝试过在任何 XML 编辑器(例如 Altova 或 Eclipse 等)中根据模式验证您的 XML。
到目前为止,您的解析错误似乎是合法的,根据架构,XML 无效。
关于java - 针对 XSD : cvc-elt. 1 的 XML 验证:找不到元素 'xxx' 的声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10211238/