July 21, 2011

XML Namespaces example with 2 XML Schemas (XSDs)

A working example of a XML document that references and contains elements from 2 XML Schema Documents (XSDs). Both the XSDs contain an element with a common name, demonstrating the utility of XML namespaces.

XSD-1: schema01.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns:s="http://example.org/s">

   <xs:import namespace="http://example.org/s" 
              schemaLocation="schema02.xsd"/>

   <xs:element name="root" type="RootType"/>

   <xs:complexType name="RootType">
     <xs:sequence>
       <xs:element name="qty" type="xs:integer" maxOccurs="unbounded"/>
       <xs:element ref="s:qty" maxOccurs="unbounded"/>
     </xs:sequence>
   </xs:complexType>
</xs:schema>

XSD-2: schema02.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
       targetNamespace="http://example.org/s"t
       xmlns:s="http://example.org/s"
       elementFormDefault="qualified">

   <xs:element name="qty" type="xs:string"/>

</xs:schema>

XML: test.xml

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="schema01.xsd" 
       xmlns:s="http://example.org/s">
   <qty>12</qty>
   <s:qty>Twelve</s:qty>
</root>

No comments:

Post a Comment