我的目标是创建一个正确引用描述结构的 XSD 文件的 XML,同时两个文件都使用 namespace (通过在 xmlns
属性中设置默认 namespace 来创建 XML)。
我可以在 XML 中指定 xsi:noNamespaceSchemaLocation
属性,它至少在一些验证器中有效(比如 http://www.validome.org/xml/validate/ )。但是当我尝试添加 namespace 时,验证器返回错误(例如:找不到元素“note”的声明。)
我准备的测试文件的最终版本附在下面。我用 xmllint
测试了它,比如:
xmllint example.xml --schema example.xsd
它起作用了,但我在参数中指定了架构位置。我的问题是:XML 文件是否正确引用了 XSD,它是否正确使用了 namespace ?为什么验证器会返回错误?
例子.xml:
<?xml version="1.0" encoding="UTF-8"?>
<note
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="example.xsd"
xmlns="http://example/note"
>
<from>Jacek</from>
<to>Agatka</to>
<body>Kocham cię!</body>
</note>
例子.xsd:
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://example/note"
targetNamespace="http://example/note"
>
<xsd:element name="note">
<xsd:complexType>
<xsd:sequence>
<xsd:element ref="from"/>
<xsd:element ref="to"/>
<xsd:element ref="body"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="from" type="xsd:string"/>
<xsd:element name="to" type="xsd:string"/>
<xsd:element name="body" type="xsd:string"/>
</xsd:schema>
最佳答案
schemaLocation
属性还应指定命名空间:
<?xml version="1.0" encoding="utf-8"?>
<note
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://example/note example.xsd"
xmlns="http://example/note">
<from>Jacek</from>
<to>Agatka</to>
<body>Kocham cię!</body>
</note>
参见文档 here .
关于xml - 如何在 XML 中指定 namespace 和架构位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16108434/