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