XML

Including Schemas from a Different targetNamespace

When you use the include element, you insert the entire referenced schema into the top-level schema and both documents must have the same targetNamespace attribute. You might also want to create schema documents that contain simpleType and complexType declarations that you can use in multiple schemas. If the multiple schemas have a different targetNamespace, you cannot use the include element for a document shared between them. Instead of using the include element, you can use the import element. If you use the import element, you can reference any data type created in the imported document and use, extend, or restrict the data type, as shown here:

  <schema targetNamespace="http://www.northwindtraders.com/Message"
      xmlns:northwindMessage="http://www.northwindtraders.com/Message"
      xmlns:northwindType="http://www.northwindtraders.com/Types"
      xmlns ="http://www.w3.org/1999/XMLSchema">
      <import schemaLocation="http://www.northwindtraders.com/        HTMLTypes.xsd"/>
      <element name="doc">
          <element ref="northwindMessage:body"/>
      </element>
      <element name="body">
          <attribute name="bodyText" type="northwindType:TextBody"/>
      </element>
  </schema>

The HTMLTypes.xsd file might look like this:

  <xsd:schema targetNamespace:xsd="http://www.northwindtraders.com/    Types"
      xmlns:northwindMessage="http://www.northwindtraders.com/Types"
      xmlns ="http://www.w3.org/1999/XMLSchema">
      <xsd:simpleType name="TextBody" base="string"
          minLength="0"
          maxLength="20"/>
  </xsd:schema>

In the top-level schema, we associated a namespace called http://www.northwindtraders.com/Types with the prefix northwindType. Using the import element, we can associate that namespace with a schema location. The application will determine how to use the schemaLocation attribute. Once you have done this, you can use the data type. An instance document for this schema is shown here:

  <?xml version="1.0"?>
  <northwindMessage:doc xmlns:northwindMessage=
      "http://www.northwindtraders.com/Message" >
      <body bodyText="Hello, world"/>
  </northwindMessage:doc>

Once again, as far as the instance document is concerned, it does not matter where the data types are defined-everything comes from the top-level document.