Nesting XML elements from different namespaces in XSD

烂漫一生 提交于 2020-01-03 19:31:27

问题


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.

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>

as well as file 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>

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>

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>

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?


回答1:


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"/>

Updated 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>


来源:https://stackoverflow.com/questions/52296668/nesting-xml-elements-from-different-namespaces-in-xsd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!