在 XSD 中嵌套来自不同命名空间的 XML 元素 [英] Nesting XML elements from different namespaces in XSD
问题描述
假设我有一个命名空间元素的 XML 架构定义,我想将其用作第二个命名空间中 XML 元素的子元素.
Assume that I have an XML schema definition for elements of a namespace that I would like to use as child elements of XML elements within a second namespace.
举个例子,假设我们有文件 foo.xsd:
As an example, suppose we have file foo.xsd:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns="urn:foo-ns" targetNamespace="urn:foo-ns"
xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="foo" type="fooType"/>
<xs:complexType name="fooType">
<xs:attribute name="id" use="required"/>
</xs:complexType>
</xs:schema>
以及文件bar.xsd:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns="urn:bar-ns"
targetNamespace="urn:bar-ns"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:foo-ns="urn:foo-ns"
elementFormDefault="qualified">
<xs:import namespace="urn:foo-ns" schemaLocation="foo.xsd"/>
<xs:element name="bar" type="barType"/>
<xs:complexType name="barType">
<xs:sequence minOccurs="0" maxOccurs="unbounded">
<xs:element name="foo" type="foo-ns:fooType"/>
</xs:sequence>
<xs:attribute name="name" use="required"/>
</xs:complexType>
</xs:schema>
然后我希望以下文件 bar.xml 是有效的 XML:
Then I would have expected the following file bar.xml to be valid XML:
<?xml version="1.0" encoding="UTF-8"?>
<bar name="myBar" xmlns="urn:bar-ns">
<foo id="myFoo" xmlns="urn:foo-ns"/>
</bar>
然而,我的 XML 验证器抱怨 foo 元素的命名空间声明;相反,它坚持以下文件是有效的:
However, my XML validator complains about the namespace declaration of the foo element; instead it insists that the following file is valid:
<?xml version="1.0" encoding="UTF-8"?>
<bar name="myBar" xmlns="urn:bar-ns">
<foo id="myFoo"/>
</bar>
我是否错误地声明了我的架构文件?我将如何设置 XSD 以使 bar.xml 的初始版本有效?
Am I declaring my schema files incorrectly? How would I set up the XSDs in order for the initial version of bar.xml to be valid?
推荐答案
在 bar.xsd 中,您必须引用 element 而不是 type foo
声明,如果你希望 foo
在 urn:bar-ns
命名空间中:
In bar.xsd you have to reference the element not the type declaration of foo
if you wish foo
to be in the urn:bar-ns
namespace:
<xs:element ref="foo-ns:foo"/>
更新了 bar.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns="urn:bar-ns"
targetNamespace="urn:bar-ns"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:foo-ns="urn:foo-ns"
elementFormDefault="qualified">
<xs:import namespace="urn:foo-ns" schemaLocation="foo.xsd"/>
<xs:element name="bar" type="barType"/>
<xs:complexType name="barType">
<xs:sequence minOccurs="0" maxOccurs="unbounded">
<xs:element ref="foo-ns:foo"/>
</xs:sequence>
<xs:attribute name="name" use="required"/>
</xs:complexType>
</xs:schema>
这篇关于在 XSD 中嵌套来自不同命名空间的 XML 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!