我有一个 XML 模式 schema.xsd
,在外部文件 types.xsd
中有自定义类型。我不知道为什么我的复杂类型 typeComplex
没有被正确验证。像 typeSimple
这样的简单类型工作正常。这有什么问题?
eclipse 说:
cvc-complex-type.2.4.a: Invalid content was found starting with element 'a'. One of '{"http://www.example.org/types":a}' is expected.
架构.xsd:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org/schema" elementFormDefault="qualified"
xmlns:t="http://www.example.org/types">
<xs:import schemaLocation="types.xsd" namespace="http://www.example.org/types" />
<xs:element name="root">
<xs:complexType>
<xs:all>
<xs:element name="simple" type="t:typeSimple" />
<xs:element name="complex" type="t:typeComplex" />
</xs:all>
</xs:complexType>
</xs:element>
</xs:schema>
类型.xsd:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org/types" xmlns="http://www.example.org/types"
elementFormDefault="qualified">
<xs:simpleType name="typeSimple">
<xs:restriction base="xs:string">
<xs:length value="3" />
</xs:restriction>
</xs:simpleType>
<xs:complexType name="typeComplex">
<xs:sequence>
<xs:element name="a" type="xs:string" />
<xs:element name="b" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:schema>
text.xml - 对 xsd 无效 - 为什么?
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns="http://www.example.org/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.example.org/schema schema.xsd " xmlns:t="http://www.example.org/types">
<simple>XXX</simple>
<complex>
<a></a> <!-- not valid here; Eclipse say: cvc-complex-type.2.4.a: Invalid content was found starting with element 'a'. One of '{"http://www.example.org/types":a}' is expected. -->
<b></b>
</complex>
</root>
最佳答案
您的实例文档被声明为命名空间“http://www.example.org/schema”中“根”类型的实例。这可以。在本文档中,您希望使用命名空间“http://www.example.org/types”中的类型,因此您已将此命名空间包含在前缀中。这也可以。
但是,当您使用“http://www.example.org/types”命名空间中包含的类型时,您将忽略在 xmlns 声明中定义的前缀。
引用这些类型的正确方法:
<root xmlns="http://www.example.org/schema"
xmlns:t="http://www.example.org/types">
<simple>XXX</simple>
<complex>
<t:a></t:a>
<t:b></t:b>
</complex>
</root>
更新
您的备选方案是:
使用非限定类型 - 只需更改您的架构定义即可生成 elementFormDefault="unqualified"
。这意味着您现在可以这样做:
<root xmlns="http://www.example.org/schema">
<simple xmlns="">XXX</simple>
<complex xmlns="">
<a></a>
<b></b>
</complex>
</root>
或者,不要使用 XSD 架构。这意味着您可以只使用格式正确的 xml:
<root>
<simple>XXX</simple>
<complex>
<a></a>
<b></b>
</complex>
</root>
关于xml - XSD:导入复杂类型不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10328695/