XML 验证期间可能存在命名空间问题

问题描述

以下带有 XSD 的 XML 导致验证错误

命名空间 'http://www.test.it' 中的元素“choices”在命名空间 'http://www.test.it' 中具有无效的子元素“choice”。预期的可能元素列表:'选择'。

这是choices.xml

<?xml version="1.0" encoding="utf-8"?>
<choices xmlns="http://www.test.it"
         xmlns:xsd="http://www.w3.org/2001/XMLSchema-instance"
         xsd:schemaLocation="http://www.test.it ./schema/choices.xsd">
    <choice>yes</choice>
</choices>

这是schema/choices.xsd

<?xml version="1.0" encoding="utf-8"?>
<xs:schema  xmlns="http://www.test.it"
            xmlns:xs="http://www.w3.org/2001/XMLSchema"
            targetNamespace="http://www.test.it">

    <xs:simpleType name="yes_or_no_t">
        <xs:restriction base="xs:string">
            <xs:enumeration value="yes" />
            <xs:enumeration value="no" />
        </xs:restriction>
    </xs:simpleType>

    <xs:element name="choices" >
        <xs:complexType>
            <xs:all>
                <xs:element name="choice" type="yes_or_no_t" />
            </xs:all>
        </xs:complexType>
    </xs:element>

</xs:schema>

我必须在 XML 中保留 xmlns="http://www.test.it"。 XML 和 XSD 是本地文件(不通过网络发布)。我宁愿将 XSD 保存在 schema 子目录中。

解决方法

有两个问题...

查找 XSD

xsi:schemaLocation 用于命名空间 XML,而不是 xsi:noNamespaceSchemaLocation

另见:

限定元素

elementFormDefault="qualified" 添加到 XSD 的架构元素。

另见: