Stylus Studio XML Editor

Table of contents

Appendices

4.3 Using Derived Types in Instance Documents

Using Derived Types in Instance Documents

In our example scenario, purchase orders are generated in response to customer orders which may involve shipping and billing addresses in different countries. The international purchase order, ipo.xml below, illustrates one such case where goods are shipped to the UK and the bill is sent to a US address. Clearly it is better if the schema for international purchase orders does not have to spell out every possible combination of international addresses for billing and shipping, and even more so if we can add new complex types of international address simply by creating new derivations of Address.

ref24XML Schema allows us to define the billTo and shipTo elements as Address types (see ipo.xsd) but to use instances of international addresses in place of instances of Address. In other words, an instance document whose content conforms to the UKAddress type will be valid if that content appears within the document at a location where an Address is expected (assuming the UKAddress content itself is valid). To make this feature of XML Schema work, and to identify exactly which derived type is intended, the derived type must be identified in the instance document. The type is identified using the xsi:type attribute which is part of the XML Schema instance namespace. In the example, ipo.xml, use of the UKAddress and USAddress derived types is identified through the values assigned to the xsi:type attributes.

NOTE: 

An International Purchase order, ipo.xml

<?xml version="1.0"?>
<ipo:purchaseOrder
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:ipo="http://www.example.com/IPO"
  orderDate="1999-12-01">

  <shipTo exportCode="1" xsi:type="ipo:UKAddress">
    <name>Helen Zoe</name>
    <street>47 Eden Street</street>
    <city>Cambridge</city>
    <postcode>CB1 1JR</postcode>
  </shipTo>

  <billTo xsi:type="ipo:USAddress">
    <name>Robert Smith</name>
    <street>8 Oak Avenue</street>
    <city>Old Town</city>
    <state>PA</state>
    <zip>95819</zip>
  </billTo>

  <items>
    <item partNum="833-AA">
      <productName>Lapis necklace</productName>
      <quantity>1</quantity>
      <USPrice>99.95</USPrice>
      <ipo:comment>Want this for the holidays<!/ipo:comment>
      <shipDate>1999-12-05</shipDate>
    </item>
  </items>
</ipo:purchaseOrder>

In [Controlling the Creation & Use of Derived Types] we describe how to prevent derived types from being used in this sort of substitution.