# XML - Managing Data Exchange/The one-to-many relationship

------------------------------------------------------------------------

```{=html}
<table cellspacing=10 cellpadding=10 border=5>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<font size=4>`{=html}`<b>`{=html}Learning
objectives`</b>`{=html}`</font>`{=html}\

-   `<font size=3>`{=html} Learn different techniques of implementing
    one-to-many relationships in XML`</font>`{=html}
-   `<font size=3>`{=html} create custom data types in an XML
    schema`</font>`{=html}
-   `<font size=3>`{=html} create empty elements with attributes in an
    XML document`</font>`{=html}
-   `<font size=3>`{=html} define a presentation layout for an XML
    document using a table with varying background colors and font
    characteristics, and display images in an XML
    stylesheet`</font>`{=html}

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
\
\
==Introduction== In a one-to-many relationship, one object can reference
several instances of another. A model is mapped into a schema whereby
each data model entity becomes a complex element type. Each data model
attribute becomes a simple element type, and the one-to-many
relationship is recorded as a sequence.\
\
**Exhibit 1:Data model for 1:m relationship**\
:::\
In the previous chapter, we introduced a simple XML schema, XML
document, and an XML stylesheet for a single entity data model. We now
include more features of each of the key aspects of XML.

### Implementing a one-to-many relationship

There are three different techniques for implementing a one-to-many
relationship:

Containment relationship: A structure is defined where one element is
contained within another. The \"contained\" element ceases to exist when
the \"container\" element is removed. For instance, where a city has
many hotels, the hotels are \"contained\" in the city.

``` XML
  <cityDetails>
    <cityName>Belmopa</cityName>
    <hotelDetails>
      <hotelName>Bull Frog Inn</hotelName>
    </hotelDetails>
    <hotelDetails>
      <hotelName>Pook's Hill Lodge</hotelName>
    </hotelDetails>
  </cityDetails>
  <cityDetails>
    <cityName>Kuala Lumpur</cityName>
    <hotelDetails>
      <hotelName>Pan Pacific Kuala Lumpur</hotelName>
    </hotelDetails>
    <hotelDetails>
      <hotelName>Mandarin Oriental Kuala Lumpur</hotelName>
    </hotelDetails>
  </cityDetails>
```

Intra-document relationships: In a case where you have one city with
many hotels, rather than a city containing hotels, a hotel will have a
\"location in\" relationship to a city. A city id is used as a reference
on the hotel element. Therefore, rather than the hotels being contained
in the city, they now just reference the city\'s id via the cityRef
attribute. This is very similar to a foreign key in a relational
database.

``` XML
  <cityDetails>
   <city ID="c1">
    <cityName>Belmopa</cityName>
   </city ID>
   <city ID="c2">
    <cityName>Kuala Lumpur</cityName>
   </city ID>
  </cityDetails>
  <hotelDetails>
    <hotel cityRef="c1">
      <hotelName>Bull Frog Inn</hotelName>
    </hotel>
    <hotel cityRef="c2">
      <hotelName>Pan Pacific Kuala Lumpur</hotelName>
    </hotel>
  </hotelDetails>
```

Inter-document relationships: The inter-document relationship is much
like the intra-document relationship. It also uses the id and idRef
attributes to assign an attribute to a parent attribute. The difference
is that the inter-document relationship is used when tables, such as the
city and hotel tables, might live in different filesystems or
tablespaces.

``` XML
  <city id="c1">
    <cityName>Belmopa</cityName>
  </city>
  <city id="c2">
    <cityName>Kuala Lumpur</cityName>
  </city>
```

``` XML
  <hotel>
    <city href="cityDetails.xml#c1"/>
    <hotelName>Bull Frog Inn</hotelName>
  </hotel>
  <hotel>
    <city href="cityDetails.xml#c2"/>
    <hotelName>Pan Pacific Kuala Lumpur</hotelName>
  </hotel>
```

**Exhibit 2:Checklist for deciding what technique to use:**

```{=html}
<table width="100%" border="1" cellspacing="0" cellpadding="0">
```
```{=html}
<tr>
```
```{=html}
<th width="30%">
```
Technique

```{=html}
</th>
```
```{=html}
<th width="25%">
```
Passing Data

```{=html}
</th>
```
```{=html}
<th width="15%">
```
Flexibility

```{=html}
</th>
```
```{=html}
<th width="30%">
```
Ease of Use

```{=html}
</th>
```
```{=html}
</tr>
```
```{=html}
<tr style="text-align:center">
```
```{=html}
<td>
```
Containment

```{=html}
</td>
```
```{=html}
<td>
```
Excellent

```{=html}
</td>
```
```{=html}
<td>
```
Fair

```{=html}
</td>
```
```{=html}
<td>
```
Excellent

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td style="text-align:center">
```
Intra-Document

```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Good

```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Good

```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Good

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td style="text-align:center">
```
Inter-Document

```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Fair

```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Excellent

```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Fair

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
## XML schema

Some of the built-in data types for an XML schema were introduced in the
previous chapter, but still, there are more that are very useful, such
as anyURI, date, time, year, and month. In addition to the built-in data
types, a custom data type can be defined by the schema designer to
accept specific data input. As we have learned, data are defined in XML
documents using markup tags defined in an XML schema. However, some
elements might not have values. An empty element tag can be used to
address this situation. An empty element tag (and any custom markup tag)
can contain attributes that add additional information about the tag
without adding extra text to the element. An example will be shown in
the chapter, using attributes in an empty element tag.

### Empty elements with attributes in XML document

Elements can have different content types depending on how each element
is defined in the XML schema. The different types are element content,
mixed content, simple content, and empty content. An XML element
consists of everything from the start of the element tag to the close of
that element tag.

-   An element with element content is the root element - everything in
    between the opening and closing tags consists of elements only.

```{=html}
<table border="0" width="85%" style="margin:auto">
```
```{=html}
<tr>
```
```{=html}
<td width="13%">
```
Example:

```{=html}
</td>
```
```{=html}
<td width="87%">
```
`<tourGuide>`{=html}

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```

```{=html}
</td>
```
```{=html}
<td>
```
    :

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```

```{=html}
</td>
```
```{=html}
<td>
```
`</tourGuide>`{=html}

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
-   A mixed content element is one that has text and as well as other
    elements between its opening and closing tags.

```{=html}
<table border="0" width="85%" style="margin:auto">
```
```{=html}
<tr>
```
```{=html}
<td width="13%">
```
Example:

```{=html}
</td>
```
```{=html}
<td width="87%">
```
`<restaurant>`{=html}My favorite restaurant is

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```

```{=html}
</td>
```
```{=html}
<td>
```
`<restaurantName>`{=html}Provino\'s Italian
Restaurant`</restaurantName>`{=html}

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```

```{=html}
</td>
```
```{=html}
<td>
```
    :

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```

```{=html}
</td>
```
```{=html}
<td>
```
`</restaurant>`{=html}

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
-   A simple content element is one that contains only text between its
    opening and closing tags.

```{=html}
<table border="0" width="85%" style="margin:auto">
```
```{=html}
<tr>
```
```{=html}
<td width="13%">
```
Example:

```{=html}
</td>
```
```{=html}
<td width="87%">
```
`<restaurantName>`{=html}Provino\'s Italian
Restaurant`</restaurantName>`{=html}

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
-   An empty content element, which is an empty element, is one that
    does not contain anything between its opening and closing tags (or
    the element tag is opened and ended with a single tag, by using /
    before the closing of the opening tag.

```{=html}
<table border="0" width="85%" style="margin:auto">
```
```{=html}
<tr>
```
```{=html}
<td width="13%">
```
Example:

```{=html}
</td>
```
```{=html}
<td width="87%">
```
\<hotelPicture filename=\"pan_pacific.jpg\" size=\"80\"

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```

```{=html}
</td>
```
```{=html}
<td>
```
        value=\"Image of Pan Pacific\"/\>

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
An empty element is useful when there is no need to specify its content
or that the information describing the element is fixed. Two examples
illustrated this concept. First, a picture element that references the
source of an image with its attributes, but has no need in specifying
text content. Second, the owner's name is fixed for a company, thus it
can specify the related information inside the owner tag using
attributes. An attribute is meta-information, information that describes
the content of the element.

### European Central Bank\'s use of XML

``` XML
<?xml version="1.0" encoding="UTF-8"?>
<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01"
xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">
    <gesmes:subject>Reference rates</gesmes:subject>
    <gesmes:Sender>
        <gesmes:name>European Central Bank</gesmes:name>
    </gesmes:Sender>
    <Cube>
        <Cube time="2004-05-28">
            <Cube currency="USD" rate="1.2246"/>
            <Cube currency="JPY" rate="135.77"/>
            <Cube currency="DKK" rate="7.4380"/>
            <Cube currency="GBP" rate="0.66730"/>
            <Cube currency="SEK" rate="9.1150"/>
            <Cube currency="CHF" rate="1.5304"/>
            <Cube currency="ISK" rate="87.72"/>
            <Cube currency="NOK" rate="8.2120"/>
        </Cube>
    </Cube>

<!--For the sake of illustration, some of the currencies are omitted
in the preceding code.Banks, consultants, currency traders,
and firms involved in international trade are the major users
of this information.-->

</gesmes:Envelope>
```

### XML schema data types

Some of the commonly used data types, such as string, decimal, integer,
and boolean, are introduced in chapter 2. The following are a few more
data types that are useful.

**Exhibit 3:Other data types:**

```{=html}
<table width="100%" border="1" cellspacing="0" cellpadding="0">
```
```{=html}
<tr>
```
```{=html}
<th width="7%">
```
Type

```{=html}
</th>
```
```{=html}
<th width="25%">
```
Format

```{=html}
</th>
```
```{=html}
<th width="18%">
```
Example

```{=html}
</th>
```
```{=html}
<th width="50%">
```
Comment

```{=html}
</th>
```
```{=html}
</tr>
```
```{=html}
<tr style="text-align:center">
```
```{=html}
<td>
```
year

```{=html}
</td>
```
```{=html}
<td>
```
YYYY

```{=html}
</td>
```
```{=html}
<td>
```
1999

```{=html}
</td>
```
```{=html}
<td>
```

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td style="text-align:center">
```
month

```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
YYYY-MM

```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
1999-03

```{=html}
</td>
```
```{=html}
<td>
```
Month type is used when the day is irrelevant for the data element

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td style="text-align:center">
```
time

```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
hh:mm:ss.sss with optional time zone indicator

```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
20:14:05

```{=html}
</td>
```
```{=html}
<td>
```
Z for UTC or one of --hh:mm or +hh:mm to indicate the difference from
UTC. This time type is used when you want the content to represent a
particular time of day that recurs every day, such as 4:15 pm.

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style="text-align:center">
```
```{=html}
<td>
```
date

```{=html}
</td>
```
```{=html}
<td>
```
YYYY-MM-DD

```{=html}
</td>
```
```{=html}
<td>
```
1999-03-14

```{=html}
</td>
```
```{=html}
<td>
```

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td style="text-align:center">
```
anyURI

```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
The domain name specified beginning with <http://>

```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
<http://www.panpacific.com>

```{=html}
</td>
```
```{=html}
<td>
```

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
### More data types

Besides the built-in data types, custom data types can be created as
required. A custom data type can be a simple type or complex type. For
simplicity, we create a custom data type that is a simple type, which
means that the element does not contain other elements or attributes. It
contains text only. The creation of a custom simple type starts from
using a built-in simple type and applying it with restrictions, or
facets, to limit the acceptable values of the tag. A custom simple type
can be nameless or named. If the custom simple type is to be used only
once, then it makes sense to not name it; thus, that custom type will
only be used in where it is defined. Since a named custom type can be
referenced (by its name), that custom type can be used wherever
necessary.

A pattern can be used to specify exactly how the content of the element
should look. For example, one might want to specify the format of a
telephone number, a postal code, or a product code. By having a defined
pattern for certain elements, the data exchanged will be uniform and the
values will be consistent when stored in a database. A useful way to set
patterns is through Regex, which will be discussed in later chapters.

### Schema examples

The following is a schema that extends the schema introduced in the
previous chapter to include a one-to-many relationship of city to hotels
with two examples of custom data types.

**Exhibit 1:Data model for 1:m relationship**

:

    :   !1:m relationship - City
        Hotel

Important, this is a continuing example, so new code is added to the
last chapter\'s example!

#### Containment example

``` XML
 <?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified">

  <!--Tour Guide-->

  <xsd:element name="tourGuide">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="city" type="cityDetails" minOccurs="1" maxOccurs="unbounded"/>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>

  <!--This will contain the City details-->

  <xsd:complexType name="cityDetails">
    <xsd:sequence>
      <xsd:element name="cityName" type="xsd:string"/>
      <xsd:element name="adminUnit" type="xsd:string"/>
      <xsd:element name="country" type="xsd:string"/>

      <!--The element Continent uses a Nameless Custom Simple Type-->

      <xsd:element name="continent">
        <xsd:simpleType>
          <xsd:restriction base="xsd:string">
            <xsd:enumeration value="Asia"/>
            <xsd:enumeration value="Africa"/>
            <xsd:enumeration value="Australia"/>
            <xsd:enumeration value="Europe"/>
            <xsd:enumeration value="North America"/>
            <xsd:enumeration value="South America"/>
            <xsd:enumeration value="Antarctica"/>
          </xsd:restriction>
        </xsd:simpleType>
      </xsd:element>
      <xsd:element name="population" type="xsd:integer"/>
      <xsd:element name="area" type="xsd:integer"/>
      <xsd:element name="elevation" type="xsd:integer"/>
      <xsd:element name="longitude" type="xsd:decimal"/>
      <xsd:element name="latitude" type="xsd:decimal"/>
      <xsd:element name="description" type="xsd:string"/>
      <xsd:element name="history" type="xsd:string"/>
      <xsd:element name="hotel" type="hotelDetails" minOccurs="1" maxOccurs="unbounded"/>
    </xsd:sequence>
  </xsd:complexType>

  <!-- This will contain the Hotel details-->

  <xsd:complexType name="hotelDetails">
    <xsd:sequence>
      <xsd:element name="hotelName" type="xsd:string"/>
      <xsd:element name="hotelPicture"/>
      <xsd:element name="streetAddress" type="xsd:string"/>
      <xsd:element name="postalCode" type="xsd:string" minOccurs="0"/>
      <xsd:element name="phone" type="xsd:string"/>
      <xsd:element name="emailAddress" type="emailAddressType" minOccurs="0"/>

      <!-- The custom simple type, emailAddressType, defined in the xsd:complexType,
           is used as the type of the emailAddress element. -->

      <xsd:element name="websiteURL" type="xsd:anyURI" minOccurs="0"/>
      <xsd:element name="hotelRating" type="xsd:integer"/>
    </xsd:sequence>
  </xsd:complexType>

  <!-- NOTE: Since postalCode, emailAddress, and websiteURL are not standard elements that
          must be provided, the minOccurs=”0” indicates that they are optional -->

  <!--This is a Named Custom SimpleType that is called from Hotel whenever someone types in an
      email address-->

  <xsd:simpleType name="emailAddressType">
    <xsd:restriction base="xsd:string">

      <!--You can learn more about this pattern by reading the Regex section.-->

      <xsd:pattern value="\w+\W*\w*@{1}\w+\W*\w+.\w+.*\w*"/>
    </xsd:restriction>
  </xsd:simpleType>
</xsd:schema>
```

#### Intra-document example

``` XML
 <?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified">

  <!--Tour Guide-->

  <xsd:element name="tourGuide">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="city" type="cityDetails" minOccurs="1" maxOccurs="unbounded"/>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>

  <!--This will contain the City details-->

  <xsd:complexType name="cityDetails">
    <xsd:sequence>
      <xsd:element name="cityID" type="xsd:ID"/>
      <xsd:element name="cityName" type="xsd:string"/>
      <xsd:element name="adminUnit" type="xsd:string"/>
      <xsd:element name="country" type="xsd:string"/>

      <!--The element Continent uses a Nameless Custom Simple Type-->

      <xsd:element name="continent">
        <xsd:simpleType>
          <xsd:restriction base="xsd:string">
            <xsd:enumeration value="Asia"/>
            <xsd:enumeration value="Africa"/>
            <xsd:enumeration value="Australia"/>
            <xsd:enumeration value="Europe"/>
            <xsd:enumeration value="North America"/>
            <xsd:enumeration value="South America"/>
            <xsd:enumeration value="Antarctica"/>
          </xsd:restriction>
        </xsd:simpleType>
      </xsd:element>
      <xsd:element name="population" type="xsd:integer"/>
      <xsd:element name="area" type="xsd:integer"/>
      <xsd:element name="elevation" type="xsd:integer"/>
      <xsd:element name="longitude" type="xsd:decimal"/>
      <xsd:element name="latitude" type="xsd:decimal"/>
      <xsd:element name="description" type="xsd:string"/>
      <xsd:element name="history" type="xsd:string"/>
     </xsd:sequence>
  </xsd:complexType>

  <!-- This will contain the Hotel details-->

  <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="hotel" type="hotelDetails" minOccurs="1" maxOccurs="unbounded"/>
      </xsd:sequence>
    </xsd:complexType>
  <xsd:complexType name="hotelDetails">
    <xsd:sequence>
      <xsd:element name="cityRef" type="xsd:IDRef"/>
      <xsd:element name="hotelName" type="xsd:string"/>
      <xsd:element name="hotelPicture"/>
      <xsd:element name="streetAddress" type="xsd:string"/>
      <xsd:element name="postalCode" type="xsd:string" minOccurs="0"/>
      <xsd:element name="phone" type="xsd:string"/>
      <xsd:element name="emailAddress" type="emailAddressType" minOccurs="0"/>

      <!-- The custom simple type, emailAddressType, defined in the xsd:complexType,
           is used as the type of the emailAddress element. -->

      <xsd:element name="websiteURL" type="xsd:anyURI" minOccurs="0"/>
      <xsd:element name="hotelRating" type="xsd:integer"/>
    </xsd:sequence>
  </xsd:complexType>

  <!-- NOTE: Since postalCode, emailAddress, and websiteURL are not standard elements that
          must be provided, the minOccurs=”0” indicates that they are optional -->

  <!--This is a Named Custom SimpleType that is called from Hotel whenever someone types in an
      email address-->

  <xsd:simpleType name="emailAddressType">
    <xsd:restriction base="xsd:string">

      <!--You can learn more about this pattern by reading the Regex section.-->

      <xsd:pattern value="\w+\W*\w*@{1}\w+\W*\w+.\w+.*\w*"/>
    </xsd:restriction>
  </xsd:simpleType>
</xsd:schema>
```

#### Inter-document example

``` XML
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified">

  <!--Tour Guide-->

  <xsd:element name="tourGuide">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="city" type="cityDetails" minOccurs="1" maxOccurs="unbounded"/>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>

  <!--This will contain the City details-->

  <xsd:complexType name="cityDetails">
    <xsd:sequence>
      <xsd:element name="cityID" type="xsd:ID"/>
      <xsd:element name="cityName" type="xsd:string"/>
      <xsd:element name="adminUnit" type="xsd:string"/>
      <xsd:element name="country" type="xsd:string"/>

      <!--The element Continent uses a Nameless Custom Simple Type-->

      <xsd:element name="continent">
        <xsd:simpleType>
          <xsd:restriction base="xsd:string">
            <xsd:enumeration value="Asia"/>
            <xsd:enumeration value="Africa"/>
            <xsd:enumeration value="Australia"/>
            <xsd:enumeration value="Europe"/>
            <xsd:enumeration value="North America"/>
            <xsd:enumeration value="South America"/>
            <xsd:enumeration value="Antarctica"/>
          </xsd:restriction>
        </xsd:simpleType>
      </xsd:element>
      <xsd:element name="population" type="xsd:integer"/>
      <xsd:element name="area" type="xsd:integer"/>
      <xsd:element name="elevation" type="xsd:integer"/>
      <xsd:element name="longitude" type="xsd:decimal"/>
      <xsd:element name="latitude" type="xsd:decimal"/>
      <xsd:element name="description" type="xsd:string"/>
      <xsd:element name="history" type="xsd:string"/>
     </xsd:sequence>
  </xsd:complexType>
```

``` XML

  <!-- This will contain the Hotel details-->

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified">

  <!--Tour Guide 2-->

  <xsd:element name="tourGuide2">
  <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="hotel" type="hotelDetails" minOccurs="1" maxOccurs="unbounded"/>
      </xsd:sequence>
    </xsd:complexType>
  <xsd:complexType name="hotelDetails">
    <xsd:sequence>
      <xsd:element name="cityRef" type="xsd:IDRef"/>
      <xsd:element name="hotelName" type="xsd:string"/>
      <xsd:element name="hotelPicture"/>
      <xsd:element name="streetAddress" type="xsd:string"/>
      <xsd:element name="postalCode" type="xsd:string" minOccurs="0"/>
      <xsd:element name="phone" type="xsd:string"/>
      <xsd:element name="emailAddress" type="emailAddressType" minOccurs="0"/>

      <!-- The custom simple type, emailAddressType, defined in the xsd:complexType,
           is used as the type of the emailAddress element. -->

      <xsd:element name="websiteURL" type="xsd:anyURI" minOccurs="0"/>
      <xsd:element name="hotelRating" type="xsd:integer"/>
    </xsd:sequence>
  </xsd:complexType>

  <!-- NOTE: Since postalCode, emailAddress, and websiteURL are not standard elements that
          must be provided, the minOccurs=”0” indicates that they are optional -->

  <!--This is a Named Custom SimpleType that is called from Hotel whenever someone types in an
      email address-->

  <xsd:simpleType name="emailAddressType">
    <xsd:restriction base="xsd:string">

      <!--You can learn more about this pattern by reading the Regex section.-->

      <xsd:pattern value="\w+\W*\w*@{1}\w+\W*\w+.\w+.*\w*"/>
    </xsd:restriction>
  </xsd:simpleType>
</xsd:schema>
```

Refers to Chapter 2 - A single entity for steps in using NetBeans to
create the above XML schema.

## XML document

`<B>`{=html}Attributes`</B>`{=html}

-   The valid element naming structure applies to attribute names as
    well
-   In a given element, all attributes' names must be unique
-   An attribute may not contain the symbol '\<' The character string
    '<' can be used to represent it
-   Each attribute must have a name and a value. (i.e.
    `<hotelPicture filename=“pan_pacific.jpg” />`{=html}, filename is
    the name and pan_pacific.jpg is the value)
-   If the assigned value itself contains a quoted string, the type of
    quotation marks must differ from those used to enclose the entire
    value. (For instance, if double quotes are used to enclose the whole
    value then use single quotes for the string:
    `<name familiar=”’Jack’”>`{=html}John Smith`</name>`{=html})

``` XML
  <?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="city_hotel.xsl"?>
<tourGuide xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="TourGuide3.xsd">

    <!--This is where you define the first city and all its attributes-->

    <city>
        <cityName>Belmopa</cityName>
        <adminUnit>Cayo</adminUnit>
        <country>Belize</country>

        <!--The content of the element “continent” must be one of the values specified in the set of
            acceptable values in the XML schema for the element “continent”-->

        <continent>South America</continent>
        <population>11100</population>
        <area>5</area>
        <elevation>130</elevation>
        <longitude>12.3</longitude>
        <latitude>123.4</latitude>
        <description>Belmopan is the capital of Belize</description>
        <history>Belmopan was established following devastation of the former capitol, Belize City ,
            by Hurricane Hattie in 1965. High ground and open space influenced the choice and
            ground-breaking began in 1966. By 1970 most government offices and operations had
            already moved to the new location. </history>

        <!--This is where you would store the name of the Hotel and its attributes-->

        <!--Notice that the hotelDetails elements did not contain the postalCode entity. The document is
            still valid, because postalCode is optional-->

        <hotel>
            <hotelName>Bull Frog Inn</hotelName>

            <!--The empty element, hotelPicture, contains attributes: “filename”, “size”, and “value”, to
                                indicate the name and location of the image file, the desired size, and
                                the description of the empty element, hotelPicture-->

            <hotelPicture filename="bull_frog_inn.jpg" size="80" value="Image of Bull Frog Inn"
                imageURL="http://www.bullfroginn.com"/>
            <streetAddress>25 Half Moon Avenue</streetAddress>
            <phone>501-822-3425</phone>

            <!--The emailAddress elements must match the pattern specified in the schema to be valid -->

            <emailAddress>bullfrog@btl.net</emailAddress>
            <websiteURL>http://www.bullfroginn.com/</websiteURL>
            <hotelRating>4</hotelRating>
        </hotel>

        <!--This is where you put the information for another Hotel-->

        <hotel>
            <hotelName>Pook's Hill Lodge</hotelName>
            <hotelPicture filename="pook_hill_lodge.jpg" size="80" value="Image of Pook's Hill
                Lodge" imageURL="http://www.global-travel.co.uk/pook1.htm"/>
            <streetAddress>Roaring River</streetAddress>
            <phone>440-126-854-1732</phone>
            <emailAddress>info@global-travel.co.uk</emailAddress>
            <websiteURL>http://www.global-travel.co.uk/pook1.htm</websiteURL>
            <hotelRating>3</hotelRating>
        </hotel>
    </city>

    <!--This is where you define another city and its attributes-->

    <city>
        <cityName>Kuala Lumpur</cityName>
        <adminUnit>Selangor</adminUnit>
        <country>Malaysia</country>
        <continent>Asia</continent>
        <population>1448600</population>
        <area>243</area>
        <elevation>111</elevation>
        <longitude>101.71</longitude>
        <latitude>3.16</latitude>
        <description>Kuala Lumpur is the capital of Malaysia and is the largest city in the nation.
        </description>
        <history>The city was founded in 1857 by Chinese tin miners and superseded Klang. In 1880
            the British government transferred their headquarters from Klang to Kuala Lumpur , and
            in 1896 it became the capital of Malaysia. </history>

        <!--This is where you put the information for a Hotel-->

        <hotel>
            <hotelName>Pan Pacific Kuala Lumpur </hotelName>
            <hotelPicture filename="pan_pacific.jpg" size="80" value="Image of Pan Pacific"
             imageURL="http://www.malaysia-hotels-discount.com/hotels/kualalumpur/pan_pacific_hotel/index.shtml"/>
            <streetAddress>Jalan Putra</streetAddress>
            <postalCode>50746</postalCode>
            <phone>1-866-260-0402</phone>
            <emailAddress>president@panpacific.com</emailAddress>
            <websiteURL>http://www.panpacific.com</websiteURL>
            <hotelRating>5</hotelRating>
        </hotel>

        <!--This is where you put the information for another Hotel-->

        <hotel>
            <hotelName>Mandarin Oriental Kuala Lumpur </hotelName>
            <hotelPicture filename="mandarin_oriental.jpg" size="80" value="Image of Mandarin
                Oriental" imageURL="http://www.mandarinoriental.com/kualalumpur"/>
            <streetAddress>Kuala Lumpur City Centre</streetAddress>
            <postalCode>50088</postalCode>
            <phone>011-603-2380-8888</phone>
            <emailAddress>mokul-sales@mohg.com</emailAddress>
            <websiteURL>http://www.mandarinoriental.com/kualalumpur/</websiteURL>
            <hotelRating>5</hotelRating>
        </hotel>
    </city>
</tourGuide>
```

`<small>`{=html}**Table 3-2: XML Document for a one-to-many relationship
--
city_hotel.xml**`</small>`{=html}

Refers to Chapter 2 - A single entity for steps in using NetBeans to
create the above XML document.

## XML style sheet

``` XML
<?xml version="1.0" encoding="UTF-8"?>
  <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="html"/>
        <xsl:template match="/">
            <html>
                <head>
                    <title>Tour Guide</title>
                </head>
                <body>
                    <h2>Cities</h2>
                    <xsl:apply-templates select="tourGuide"/>
                </body>
            </html>
        </xsl:template>
        <xsl:template match="tourGuide">
            <xsl:for-each select="city">
                <xsl:text>City: </xsl:text>
                <xsl:value-of select="cityName"/>
                <br/>
                <xsl:text>Population: </xsl:text>
                <xsl:value-of select="population"/>
                <br/>
                <xsl:text>Country: </xsl:text>
                <xsl:value-of select="country"/>
                <br/>

                <xsl:for-each select="hotel">
                    <xsl:text>Hotel: </xsl:text>
                    <xsl:value-of select="hotelName"/>
                    <br/>
                </xsl:for-each>

               <br/>
            </xsl:for-each>
        </xsl:template>
  </xsl:stylesheet>
```

## Summary

+----------------------------------------------------------------------+
| Besides the simple built-in data types (e.g, year, month, time,      |
| anyURI, and date) schema designers may create custom data types to   |
| suit their needs. A simple custom data type can be created from one  |
| of the built-in data types by applying to it some restrictions,      |
| facets (enumerations that specify a set of acceptable values), or    |
| specific patterns.                                                   |
|                                                                      |
| An empty element does not contain any text, however, it may contain  |
| attributes to provide additional information about that element.     |
|                                                                      |
| The presentation layout for displaying a HTML page can include code  |
| for style tags, background color, font size, font weight, and        |
| alignment. Table tags can be used to organize the layout of content  |
| in a HTML page, and images can also be displayed using an image tag. |
+----------------------------------------------------------------------+
|                                                                      |
+----------------------------------------------------------------------+

## Exercises

In order to learn more about the one-to-many relationship,
exercises are provided.\

## Answers

In order to learn more about the one-to-many relationship,
answers are provided to go with the exercises
above.


# XML - Managing Data Exchange/The one-to-one relationship

+----------------------------------------------------------------------+
| `<span style="font-size:large;">`{=html}`<b>`{=html}Learning         |
| objectives`</b>`{=html}`</span>`{=html}\                             |
|                                                                      |
| -   `<span style="font-size:medium;">`{=html}Create a schema for a   |
|     data model containing a 1:1 relationship `</span>`{=html}        |
| -   `<span style="font-size:medium;">`{=html}Place restrictions on   |
|     elements or attributes in an XML schema`</span>`{=html}          |
| -   `<span style="font-size:medium;">`{=html}Specify fixed or        |
|     default values for an element in an XML schema`</span>`{=html}   |
+----------------------------------------------------------------------+

## Introduction

In the previous chapter, some new features of XML schemas, documents,
and stylesheets were introduced as well as how to model a one-to-many
relationship. In this chapter, we will introduce the modeling of a
one-to-one relationship in XML. We will also introduce more features of
an XML schema.

## A one-to-one (1:1) relationship

The following diagram shows a one-to-one and a one-to-many relationship.
The one-to-one relationship records each country as a single top
destination.

![](xmldm1to1.png "xmldm1to1.png")

**Exhibit 4-1: Data model for a 1:1 relationship**

## XML schema

A one-to-one (1:1) relationship is represented in the data model in
Exhibit 4-1. The addition of country and destination to the data model
allows the 1:1 relationship named topDestination. A country has many
different destinations, but only one top destination. The XML schema in
Exhibit 4-2 shows how to represent a 1:1 relationship in an XML schema.

### XML schema example

``` XML
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified">
<!--
Tour Guide
-->
 <xsd:element name="tourGuide">
  <xsd:complexType>
   <xsd:sequence>
    <xsd:element name="country" type="countryDetails" minOccurs="1" maxOccurs="unbounded" />
   </xsd:sequence>
  </xsd:complexType>
 </xsd:element>
<!--
Country
-->
 <xsd:complexType name="countryDetails">
  <xsd:sequence>
   <xsd:element name="countryName" type="xsd:string" minOccurs="1" maxOccurs="1"/>
   <xsd:element name="population" type="xsd:integer" minOccurs="0" maxOccurs="1" default="0"/>
   <xsd:element name="continent" minOccurs="0" maxOccurs="1">
    <xsd:simpleType>
     <xsd:restriction base="xsd:string">
      <xsd:enumeration value="Asia"/>
      <xsd:enumeration value="Africa"/>
      <xsd:enumeration value="Australasia"/>
      <xsd:enumeration value="Europe"/>
      <xsd:enumeration value="North America"/>
      <xsd:enumeration value="South America"/>
      <xsd:enumeration value="Antarctica"/>
     </xsd:restriction>
    </xsd:simpleType>
   </xsd:element>
   <xsd:element name="topDestination" type="destinationDetails" minOccurs="0" maxOccurs="1"/>
   <xsd:element name="destination" type="destinationDetails" minOccurs="0" maxOccurs="unbounded"/>
  </xsd:sequence>
 </xsd:complexType>
<!--
Destination
-->
 <xsd:complexType name="destinationDetails">
  <xsd:all>
   <xsd:element name="destinationName" type="xsd:string"/>
   <xsd:element name="description" type="xsd:string"/>
   <xsd:element name="streetAddress" type="xsd:string" minOccurs="0"/>
   <xsd:element name="telephoneNumber" type="xsd:string" minOccurs="0"/>
   <xsd:element name="websiteURL" type="xsd:anyURI" minOccurs="0"/>
  </xsd:all>
 </xsd:complexType>
</xsd:schema>
```

\
`<small>`{=html}**Exhibit 4-2: XML Schema for a one-to-one
relationship**`</small>`{=html}

### New elements in schema

\
Let's examine the new elements and attributes in the schema in Exhibit
4-2.

-   Country is a complex type defined in City to represent the 1:M
    relationship between a country and its cities.
-   Destination is a complex type defined in Country to represent the
    1:M relationship between a country and its many destinations.
-   topDestination is a complex type defined in Country to represent the
    1:1 relationship between a country and its top destination.

### Restrictions in schema

\
Placing restrictions on elements was introduced in the previous chapter;
however, there are more potentially useful restrictions that can be
placed on an element. Restrictions can be placed on elements and
attributes that affect how the processor handles whitespace characters:

``` XML
<xsd:element name="streetAddress">
 <xsd:simpleType>
  <xsd:restriction base="xsd:string">
   <xsd:whiteSpace value="preserve"/>
  </xsd:restriction>
 </xsd:simpleType>
</xsd:element>
```

#### White space & length constraints

The whiteSpace constraint is set to \"preserve\", which means that the
XML processor **will not** remove any white space characters. Other
useful restrictions include the following:

-   Replace -- the XML processor will replace all whitespace characters
    with spaces.

:

    :   `<xsd:whiteSpace value="replace"/>`{=html}

-   Collapse -- The processor will remove all whitespace characters.

:

    :   `<xsd:whiteSpace value="collapse"/>`{=html}

-   Length, maxLength, minLength---the length of the element can be
    fixed or can have a predefined range.

:

    :   `<xsd:length value="8"/>`{=html}
    :   `<xsd:minLength value="5"/>`{=html}
    :   `<xsd:maxLength value="8"/>`{=html}

#### Order indicators

In addition to placing restrictions on elements, order indicators can be
used to define in what order elements should occur.

##### All indicator

The `<all>`{=html} indicator specifies by default that the child
elements can appear in any order and that each child element must occur
once and only once:

``` XML
<xsd:element name="person">
 <xsd:complexType>
  <xsd:all>
   <xsd:element name="firstname" type="xsd:string"/>
   <xsd:element name="lastname" type="xsd:string"/>
  </xsd:all>
 </xsd:complexType>
</xsd:element>
```

##### Choice indicator

The `<choice>`{=html} indicator specifies that either one child element
or another can occur:

``` XML
<xsd:element name="person">
 <xsd:complexType>
  <xsd:choice>
   <xsd:element name="employee" type="employee"/>
   <xsd:element name="visitor" type="visitor"/>
  </xsd:choice>
 </xsd:complexType>
</xsd:element>
```

##### Sequence indicator

The `<sequence>`{=html} indicator specifies that the child elements must
appear in a specific order:

``` XML
<xsd:element name="person">
 <xsd:complexType>
  <xsd:sequence>
   <xsd:element name="firstname" type="xsd:string"/>
   <xsd:element name="lastname" type="xsd:string"/>
  </xsd:sequence>
 </xsd:complexType>
</xsd:element>
```

## XML document

\
The XML document in Exhibit 4-3 shows how the new elements (country and
destination) defined in the XML schema found in Exhibit 4-2 are used in
an XML document. Note that the child elements of
`<topDestination>`{=html} can appear in any order because of the
`<xsd:all>`{=html} order indicator used in the schema.

``` XML
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="newXMLSchema.xsl" media="screen"?>
<tourGuide xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="XMLSchema.xsd">
<!--
Malaysia
-->
<country>
   <countryName>Malaysia</countryName>
   <population>22229040</population>
   <continent>Asia</continent>
   <topDestination>
    <description>A popular duty-free island north of Penang.</description>
    <destinationName>Pulau Langkawi</destinationName>
   </topDestination>
   <destination>
    <destinationName>Muzium Di-Raja</destinationName>
    <description>The original palace of the Sultan</description>
    <streetAddress>122 Muzium Road</streetAddress>
    <telephoneNumber>48494030</telephoneNumber>
    <websiteURL>www.muziumdiraja.com</websiteURL>
   </destination>
   <destination>
    <destinationName>Kinabalu National Park</destinationName>
    <description>A national park</description>
    <streetAddress>54 Ocean View Drive</streetAddress>
    <telephoneNumber>4847101</telephoneNumber>
    <websiteURL>www.kinabalu.com</websiteURL>
   </destination>
  </country>
<!--
Belize
-->
  <country>
   <countryName>Belize</countryName>
   <population>249183</population>
   <continent>South America</continent>
   <topDestination>
    <destinationName>San Pedro</destinationName>
    <description>San Pedro is an island off the coast of Belize</description>
   </topDestination>
   <destination>
    <destinationName>Belize City</destinationName>
    <description>Belize City is the former capital of Belize</description>
    <websiteURL>www.belizecity.com</websiteURL>
   </destination>
   <destination>
    <destinationName>Xunantunich</destinationName>
    <description>Mayan ruins</description>
    <streetAddress>4 High Street</streetAddress>
    <telephoneNumber>011770801</telephoneNumber>
   </destination>
  </country>
  </tourGuide>
```

`<small>`{=html}**Exhibit 4-3: XML Document for a one-to-one
relationship**`</small>`{=html}

## Summary

  -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  Schema designers may place restrictions on the length of elements and on how the processor handles white space. Schema designers may also specify fixed or default values for an element. Order indicators can be used to specify the order in which elements must appear in an XML document.
  -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

## Exercises

\

## Answers


# XML - Managing Data Exchange/The many-to-many relationship

+----------------------------------------------------------------------+
| **Learning objectives**                                              |
|                                                                      |
| -   Learn different methods to represent a many-to-many relationship |
|     using XML                                                        |
| -   Create XML schemas using the \"Eliminate\" and \"ID/IDREF\"      |
|     methods to structure content based on a many-to-many             |
|     relationship                                                     |
| -   Create the corresponding XML documents for the \"Eliminate\" and |
|     \"ID/IDREF\" methods                                             |
| -   Learn to use the key function in an XML stylesheet to format     |
|     data structured with the \"ID/IDREF\" method                     |
| -   Create a basic XML stylesheet that incorporates the key function |
+----------------------------------------------------------------------+
|                                                                      |
+----------------------------------------------------------------------+

## Introduction

In the previous chapters, you learned how to use XML to structure and
format data based on one-to-one and one-to-many relationships. Because
XML provides the means to model data using hierarchical parent-child
relationships, the one-to-one and one-to-many relationships are
relatively simple to represent in XML. However, this hierarchical
parent-child structure is difficult to use to model the many-to-many
relationship, a common relationship between entities in many situations.

In this chapter, we will explore the pros and cons of a few methods that
are used to model a many-to-many relationship in XML; these methods
offer compromises in overcoming the problems that arise when applying
this relationship to XML. In particular, we will see examples of how to
model the many-to-many relationship using two different methods,
\"Eliminate\" and \"ID/IDREF.\" Additionally, in the XML stylesheet, we
will learn how to implement the key function to display the data that
was modeled using the \"ID/IDREF\" method.

## Problems: many-to-many relationship

In XML, the parent-child relationship is most commonly used to represent
a relationship. This can easily be applied to a one-to-one or
one-to-many relationship. A many-to-many relationship is not supported
directly by XML; the parent-child relationship will not work as each
element may only have a single parent element. There are couple of
possible solutions to get around this.

## Solutions: many-to-many relationship

### Eliminate

**Create XML documents that eliminate the need for a many-to-many
relationship**\
By limiting the extent of information that is conveyed, you can get
around the need for a many-to-many relationship. Instead of trying to
have one XML document encompass all of the information, separate the
information where one document describes only one of the entities that
participates in the many-to-many relationship. Using our tourGuide
relationship for example, one way for us to accomplish this would be
creating a separate XML document for each hotel. The relationship with
amenity would ultimately then become a one-to-many. This method is more
suitable for situations in which the scope of data exchange can be
limited to subsets of data. However, using this method for more broadly
scoped data exchange, you may repeat data several times, especially if
there are many attributes. To avoid this redundancy, use the ID/IDREF
method.

### ID/IDREF

**Represent the many-to-many relationship using unique identifiers**\
Although not the most user-friendly way to handle this problem, one way
of getting around the many-to-many relationship is by creating keys that
would uniquely identify each entity. To do this, an element with ID or
IDREF attributes-types must be specified within the XML schema. To use a
data modeling analogy, ID is similar to the primary key, and IDREF is
similar to the foreign key.

## Many-to-many relationship data model

**Exhibit 1: Data model for a m:m relationship**\
!Data Model for a m:m
relationship

The relationship reads, *a hotel can have many amenities, and an amenity
can exist at many hotels*.

As you will notice, in order to represent a many-to-many relationship,
two entities were added. The middle entity is necessary for the data
model to represent an associative entity that stores data about the
relationship between hotel and amenity. Using our Tour Guide example,
\"Amenity\" was added to represent a list of possible amenities that a
hotel can possess.

The following examples illustrate methods to represent a many-to-many
relationship in XML.

## Eliminate: sample solution

In this example, the many-to-many relationship has been converted to a
one-to-many relationship.

### XML schema

**Exhibit 2: XML schema for \"Eliminate\" method**

``` XML
<?xml version="1.0" encoding="UTF-8" ?>
<!--
     Document   : amenity1.xsd
     Created on : February 4, 2006
     Author     : Dr. Rick Watson
-->
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified">
    <xsd:element name="hotelGuide">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="hotel" type="hotelDetails" minOccurs="1" maxOccurs="unbounded"/>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
    <xsd:simpleType name="emailAddressType">
        <xsd:restriction base="xsd:string">
            <xsd:pattern value="\w+\W*\w*@{1}\w+\W*\w+.\w+.*\w*"/>
        </xsd:restriction>
    </xsd:simpleType>
    <xsd:complexType name="hotelDetails">
        <xsd:sequence>
            <xsd:element name="hotelPicture"/>
            <xsd:element name="hotelName" type="xsd:string"/>
            <xsd:element name="streetAddress" type="xsd:string"/>
            <xsd:element name="postalCode" type="xsd:string" minOccurs="0"/>
            <xsd:element name="telephoneNumber" type="xsd:string"/>
            <xsd:element name="emailAddress" type="emailAddressType" minOccurs="0"/>
            <xsd:element name="websiteURL" type="xsd:anyURI" minOccurs="0"/>
            <xsd:element name="hotelRating" type="xsd:integer" default="0"/>
            <xsd:element name="lowerPrice" type="xsd:positiveInteger"/>
            <xsd:element name="upperPrice" type="xsd:positiveInteger"/>
            <xsd:element name="amenity" type="amenityValue" minOccurs="0" maxOccurs="unbounded"/>
        </xsd:sequence>
    </xsd:complexType>
    <xsd:complexType name="amenityValue">
        <xsd:sequence>
            <xsd:element name="amenityType" type="xsd:string"/>
            <xsd:element name="amenityOpenHour" type="xsd:time"/>
            <xsd:element name="amenityCloseHour" type="xsd:time"/>
        </xsd:sequence>
    </xsd:complexType>
</xsd:schema>
```

### XML document

**Exhibit 3: XML document for \"Eliminate\" method**

``` XML
<?xml version="1.0" encoding="UTF-8"?>
<!--
     Document   : amenity1.xml
     Created on : February 4, 2006
     Author     : Dr. Rick Watson
-->
<hotelGuide xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="amenity1.xsd">
    <hotel>
        <hotelPicture/>
        <hotelName>Narembeen Hotel</hotelName>
        <streetAddress>Churchill Street</streetAddress>
        <telephoneNumber>+61 (08) 9064 7272</telephoneNumber>
        <emailAddress>narempub@oz.com.au</emailAddress>
        <hotelRating>1</hotelRating>
        <lowerPrice>50</lowerPrice>
        <upperPrice>100</upperPrice>
        <amenity>
            <amenityType>Restaurant</amenityType>
            <amenityOpenHour>06:00:00</amenityOpenHour>
            <amenityCloseHour>22:00:00 </amenityCloseHour>
        </amenity>
        <amenity>
            <amenityType>Pool</amenityType>
            <amenityOpenHour>06:00:00</amenityOpenHour>
            <amenityCloseHour>18:00:00 </amenityCloseHour>
        </amenity>
        <amenity>
            <amenityType>Complimentary Breakfast</amenityType>
            <amenityOpenHour>07:00:00</amenityOpenHour>
            <amenityCloseHour>10:00:00 </amenityCloseHour>
        </amenity>
    </hotel>
    <hotel>
        <hotelPicture/>
        <hotelName>Narembeen Caravan Park</hotelName>
        <streetAddress>Currall Street</streetAddress>
        <telephoneNumber>+61 (08) 9064 7308</telephoneNumber>
        <emailAddress>naremcaravan@oz.com.au</emailAddress>
        <hotelRating>1</hotelRating>
        <lowerPrice>20</lowerPrice>
        <upperPrice>30</upperPrice>
        <amenity>
            <amenityType>Pool</amenityType>
            <amenityOpenHour>10:00:00</amenityOpenHour>
            <amenityCloseHour>22:00:00 </amenityCloseHour>
        </amenity>
    </hotel>
</hotelGuide>
```

## ID/IDREF: sample solution

To avoid redundancy, we create a separate element, \"amenity,\" which is
included at the top of the schema along with \"hotel.\" Remember, the
data types ID and IDREF are synonymous with the primary key and foreign
key, respectively. For every foreign key (IDREF), there must be a
matching primary key (ID). Note that the IDREF data type has to be an
alphanumeric string.

The following example illustrates the ID/IDREF approach. Notice that the
ID for the amenity pool is defined as \"k1,\" and every hotel with a
pool as an amenity references \"k1,\" using IDREF. If the IDREF does not
match any ID, then the document will not validate.

### XML schema

**Exhibit 4: XML schema for \"ID/IDREF\" method**

``` XML
<?xml version="1.0" encoding="UTF-8" ?>
<!--
     Document   : amenity2.xsd
     Created on : February 4, 2006
     Author     : Dr. Rick Watson
-->
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified">
    <xsd:element name="hotelGuide">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="hotel" type="hotelDetails" minOccurs="1" maxOccurs="unbounded"/>
                <xsd:element name="amenity" type="amenityList" minOccurs="1" maxOccurs="unbounded"/>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
    <xsd:simpleType name="emailAddressType">
        <xsd:restriction base="xsd:string">
            <xsd:pattern value="\w+\W*\w*@{1}\w+\W*\w+.\w+.*\w*"/>
        </xsd:restriction>
    </xsd:simpleType>
    <xsd:complexType name="hotelDetails">
        <xsd:sequence>
            <xsd:element name="hotelPicture"/>
            <xsd:element name="hotelName" type="xsd:string"/>
            <xsd:element name="streetAddress" type="xsd:string"/>
            <xsd:element name="postalCode" type="xsd:string" minOccurs="0"/>
            <xsd:element name="telephoneNumber" type="xsd:string"/>
            <xsd:element name="emailAddress" type="emailAddressType" minOccurs="0"/>
            <xsd:element name="websiteURL" type="xsd:anyURI" minOccurs="0"/>
            <xsd:element name="hotelRating" type="xsd:integer" default="0"/>
            <xsd:element name="lowerPrice" type="xsd:positiveInteger"/>
            <xsd:element name="upperPrice" type="xsd:positiveInteger"/>
            <xsd:element name="amenities" type="amenityDesc" minOccurs="0" maxOccurs="unbounded"/>
        </xsd:sequence>
    </xsd:complexType>
    <xsd:complexType name="amenityDesc">
        <xsd:sequence>
            <xsd:element name="amenityIDREF" type="xsd:IDREF"/>
            <xsd:element name="amenityOpenHour" type="xsd:time"/>
            <xsd:element name="amenityCloseHour" type="xsd:time"/>
        </xsd:sequence>
    </xsd:complexType>
    <xsd:complexType name="amenityList">
        <xsd:sequence>
            <xsd:element name="amenityID" type="xsd:ID"/>
            <xsd:element name="amenityType" type="xsd:string"/>
        </xsd:sequence>
    </xsd:complexType>
</xsd:schema>
```

### XML document

**Exhibit 5: XML document for \"ID/IDREF\" method**

``` XML
<?xml version="1.0" encoding="UTF-8"?>
<!--
     Document   : amenity2.xml
     Created on : February 4, 2006
     Author     : Dr. Rick Watson
-->
<?xml-stylesheet href="amenity2.xsl" type="text/xsl" media="screen"?>
<hotelGuide xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="amenity2.xsd">
    <hotel>
        <hotelPicture/>
        <hotelName>Narembeen Hotel</hotelName>
        <streetAddress>Churchill Street</streetAddress>
        <telephoneNumber>+61 (08) 9064 7272</telephoneNumber>
        <emailAddress>narempub@oz.com.au</emailAddress>
        <hotelRating>1</hotelRating>
        <lowerPrice>50</lowerPrice>
        <upperPrice>100</upperPrice>
        <amenities>
            <amenityIDREF>k2</amenityIDREF>
            <amenityOpenHour>06:00:00</amenityOpenHour>
            <amenityCloseHour>22:00:00 </amenityCloseHour>
        </amenities>
        <amenities>
            <amenityIDREF>k1</amenityIDREF>
            <amenityOpenHour>06:00:00</amenityOpenHour>
            <amenityCloseHour>18:00:00 </amenityCloseHour>
        </amenities>
        <amenities>
            <amenityIDREF>k5</amenityIDREF>
            <amenityOpenHour>07:00:00</amenityOpenHour>
            <amenityCloseHour>10:00:00 </amenityCloseHour>
        </amenities>
    </hotel>
    <hotel>
        <hotelPicture/>
        <hotelName>Narembeen Caravan Park</hotelName>
        <streetAddress>Currall Street</streetAddress>
        <telephoneNumber>+61 (08) 9064 7308</telephoneNumber>
        <emailAddress>naremcaravan@oz.com.au</emailAddress>
        <hotelRating>1</hotelRating>
        <lowerPrice>20</lowerPrice>
        <upperPrice>30</upperPrice>
        <amenities>
            <amenityIDREF>k1</amenityIDREF>
            <amenityOpenHour>10:00:00</amenityOpenHour>
            <amenityCloseHour>22:00:00 </amenityCloseHour>
        </amenities>
    </hotel>
    <amenity>
        <amenityID>k1</amenityID>
        <amenityType>Pool</amenityType>
    </amenity>
    <amenity>
        <amenityID>k2</amenityID>
        <amenityType>Restaurant</amenityType>
    </amenity>
    <amenity>
        <amenityID>k3</amenityID>
        <amenityType>Fitness room</amenityType>
    </amenity>
    <amenity>
        <amenityID>k4</amenityID>
        <amenityType>Complimentary breakfast</amenityType>
    </amenity>
    <amenity>
        <amenityID>k5</amenityID>
        <amenityType>in-room data port</amenityType>
    </amenity>
    <amenity>
        <amenityID>k6</amenityID>
        <amenityType>Water slide</amenityType>
    </amenity>
</hotelGuide>
```

### Key function: XML stylesheet

In order to set up an XML stylesheet using the ID/IDREF method for a
many-to-many relationship, the key function should be used. In the
stylesheet, the \<xsl:key\> element specifies the index, which is used
to return a node-set from the XML document.

A key consists of the following:

1\. the node that has the key\
2. the name of the key\
3. the value of a key

The following XML stylesheet illustrates how to use the key function to
present content that is structured in a many-to-many relationship.

### XML stylesheet

**Exhibit 6: XML stylesheet for \"ID/IDREF\" method**

``` XML
<?xml version="1.0" encoding="UTF-8"?>
<!--
     Document   : amenity2.xsl
     Created on : February 4, 2006
     Author     : Dr. Rick Watson
-->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:key name="amList" match="amenity" use="amenityID"/>
    <xsl:output method="html"/>
    <xsl:template match="/">
        <html>
            <head>
                <title>Hotel Guide</title>
            </head>
            <body>
                <h2>Hotels</h2>
                <xsl:apply-templates select="hotelGuide"/>
            </body>
        </html>
    </xsl:template>
    <xsl:template match="hotelGuide">
        <xsl:for-each select="hotel">
            <xsl:value-of select="hotelName"/>
            <br/>
            <xsl:for-each select="amenities">
                <xsl:value-of select="key('amList',amenityIDREF)/amenityType"/>
                <xsl:text>   </xsl:text>
                <xsl:value-of select="amenityOpenHour"/> -
                <xsl:value-of select="amenityCloseHour"/>
                <BR/>
            </xsl:for-each>
            <br/>
            <br/>
        </xsl:for-each>
        <br/>
    </xsl:template>
</xsl:stylesheet>
```

## Expedia.de: XML and affiliate marketing

+----------------------------------------------------------------------+
| Expedia.de is the German subsidiary of expedia.com, the              |
| internet-based travel agency headquartered in Bellevue, Washington,  |
| USA. It offers its customers the booking of airline tickets, car     |
| rentals, vacation packages and various other attractions and         |
| services via its website and by phone. Its websites attract more     |
| than 70 million visitors each month. Currently expedia.com employs   |
| 4.600 employees serving customers in the United States, Canada, the  |
| UK, France, Germany, Italy, and Australia.                           |
|                                                                      |
| For marketing purposes expedia.de set up an affiliate marketing      |
| program. Affiliate marketing is a way to reach potential customers   |
| without any financial risk for the company intending to advertise    |
| (merchant). The merchant gives website owners, which are called      |
| affiliates, the opportunity to refer to the merchant page, offering  |
| commission-based monetary rewards as incentives. In the case of      |
| Expedia.de the affiliate partners receive a commission every time    |
| users from their websites book travel on expedia.de. So the          |
| affiliates can concentrate on selling and the merchant takes care of |
| handling the transactions.                                           |
|                                                                      |
| To ease the business of the affiliate partners -- and of course to   |
| make the program more attractive -- Expedia.de offers its partners a |
| service called xmlAdEd. xmlAdEd is a service providing current       |
| product information on using XML. Affiliates using this service are  |
| able to request more than 8 million of travel offerings in XML       |
| format via HTTP-request. The data is updated several times a day. In |
| the HTTP-request you can set certain parameters such as location,    |
| price, airport code, \...                                            |
|                                                                      |
| The use of XML in this case gives the affiliates several             |
| advantages:\                                                         |
| - Efficient and flexible processing of the data because of           |
| separation of structure, content and style.\                         |
| - Platform-independent processing of the data.\                      |
| - Lossless conversion into other file formats.\                      |
| - Easy integration in their websites.\                               |
| - Possibility to create an own web shop in individual design         |
|                                                                      |
| By providing their affiliates product information in XML, expedia.de |
| not only eases the business of their partners, but also ensures that |
| customers receive consistent, up-to-date information on their        |
| services.                                                            |
+----------------------------------------------------------------------+

### Summary

  ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  When describing a many-to-many relationship in XML, there are a few solutions available for designers to use. In choosing how to represent the many-to-many relationship, the designer not only must consider the most efficient way to represent the information, but also the audience for which the document is intended and how the document will be used.
  ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

## References

<http://www-128.ibm.com/developerworks/xml/library/x-xdm2m.html>

<http://www.w3.org/TR/xslt#key>

## Exercises

## Answers


# XML - Managing Data Exchange/Recursive relationships

+----------------------------------------------------------------------+
| `<font size=4>`{=html}`<b>`{=html}Learning                           |
| objectives`</b>`{=html}`</font>`{=html}\                             |
|                                                                      |
| -   Understand the concept of a recursive relationship               |
| -   Create a schema for a one-to-one recursive relationship          |
| -   Create a schema for a one-to-many recursive relationship         |
| -   Create a schema for a many-to-many recursive relationship        |
| -   Define a unique identifier in a schema                           |
| -   Create a primary key/foreign key relationship                    |
+----------------------------------------------------------------------+

\
\

## Introduction

Recursive relationships are an interesting and more complex concept than
the relationships you have seen in the previous chapters. A recursive
relationship occurs when there is a relationship between an entity and
itself. For example, a one-to-many recursive relationship occurs when an
employee is the manager of other employees. The employee entity is
related to itself, and there is a one-to-many relationship between one
employee (the manager) and many other employees (the people who report
to the manager). Because of the more complex nature of these
relationships, we will need slightly more complex methods of mapping
them to a schema and displaying them in a style sheet.

## The one-to-one recursive relationship

Continuing with the tour guide model, we will develop a schema that
shows cities that have hosted the Olympics and the previous host city.
Since the previous host is another city and only one city can be the
previous host this is a one to one recursive relationship.

:

    :   !Recursive

### host.xsd (XML schema for a one-to-one recursive model)

``` XML
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
attributeFormDefault="unqualified">

<xsd:element name="cities">
  <xsd:complexType>
    <xsd:sequence>
      <xsd:element name="city" type="cityType" maxOccurs="unbounded"/>
    </xsd:sequence>
  </xsd:complexType>
</xsd:element>

<xsd:complexType name="cityType">
  <xsd:sequence>
    <xsd:element name="cityID" type="xsd:ID"/>
     <xsd:element name="cityName" type="xsd:string"/>
     <xsd:element name="cityCountry" type="xsd:string"/>
     <xsd:element name="cityPop" type="xsd:integer"/>
     <xsd:element name="cityHostYr" type="xsd:integer"/>
     <xsd:element name="cityPreviousHost" type="xsd:IDREF" minOccurs="0" maxOccurs="1"/>
  </xsd:sequence>
</xsd:complexType>
</xsd:schema>
```

**`<SMALL>`{=html}Exhibit 1: XML schema for Host City
Entity`</SMALL>`{=html}**

### host.xml (XML document for a one-to-one recursive model)

``` XML
<?xml version="1.0" encoding="UTF-8"?>
<cities xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xsi:noNamespaceSchemaLocation='host.xsd'>
  <city>
    <cityID>c1</cityID>
    <cityName>Atlanta</cityName>
    <cityCountry>USA</cityCountry>
    <cityPop>4000000</cityPop>
    <cityHostYr>1996</cityHostYr>
  </city>
  <city>
    <cityID>c2</cityID>
    <cityName>Sydney</cityName>
    <cityCountry>Australia</cityCountry>
    <cityPop>4000000</cityPop>
    <cityHostYr>2000</cityHostYr>
    <cityPreviousHost>c1</cityPreviousHost>
  </city>
  <city>
    <cityID>c3</cityID>
    <cityName>Athens</cityName>
    <cityCountry>Greece</cityCountry>
    <cityPop>3500000</cityPop>
    <cityHostYr>2004</cityHostYr>
    <cityPreviousHost>c2</cityPreviousHost>
  </city>
</cities>
```

`<SMALL>`{=html}**Exhibit 2: XML Document for Olympic Host
City**`</SMALL>`{=html}

## The one-to-many recursive relationship

A hypothetical sports team is divided into squads with each squad having
a captain. Every person on the team is a player, regardless of whether
they are a squad captain. Since a squad captain is a player, this
situation meets the definition of a recursive relationship---a squad
captain is also a player and has a one-to-many relationship with the
other players. This is a one-to-many recursive relationship because one
captain has many players under him/her. See the example below for how to
model the relationship.

### team.xsd (XML schema for a one-to-many recursive model)

``` XML
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified">
<xsd:element name="team">
  <xsd:complexType>
    <xsd:sequence>
      <xsd:element name="player" type="playerType" maxOccurs="unbounded"/>
    </xsd:sequence>
  </xsd:complexType>
</xsd:element>
  <xsd:complexType name="playerType">
    <xsd:sequence>
      <xsd:element name="playerID" type="xsd:ID"/>
      <xsd:element name="playerName" type="xsd:string"/>
      <xsd:element name="playerCap" type="playerC" minOccurs="0" maxOccurs="unbounded"/>
    </xsd:sequence>
  </xsd:complexType>
  <xsd:complexType name="playerC">
    <xsd:sequence>
      <xsd:element name="memberOf" type="xsd:IDREF"/>
    </xsd:sequence>
  </xsd:complexType>
</xsd:schema>
```

`<SMALL>`{=html}**Exhibit 3: XML schema for Team
Entity**`</SMALL>`{=html}

### team.xml (XML document for a one-to-many recursive model)

``` XML
<?xml version="1.0" encoding="UTF-8"?>
<team xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xsi:noNamespaceSchemaLocation='Recursive1toMSchema.xsd'>
<player>
   <playerID>c1</playerID>
   <playerName>Tommy Jones</playerName>
   <playerCap>
      <memberof>c3</memberof>
   </playerCap>
</player>
<player>
   <playerID>c2</playerID>
   <playerName>Eddie Thomas</playerName>
   <playerCap>
      <memberof>c3</memberof>
   </playerCap>
</player>
<player>
   <playerID>c3</playerID>
   <playerName>Sean McCombs</playerName>
</player>
<player>
   <playerID>c4</playerID>
   <playerName>Patrick O’Shea</playerName>
   <playerCap>
      <memberof>c3</memberof>
    </playerCap>
</player>
</team>
```

`<SMALL>`{=html}**Exhibit 4: XML Document for Team
Entity**`</SMALL>`{=html}

#### Natural one-to-many recursive structure

A more natural approach for most one-to-many recursive relationships is
to use XML\'s hierarchical nature to directly represent the heirarchy.
Consider Locations:

``` XML
<?xml version="1.0" encoding="UTF-8"?>
<location type="country">
  <name>USA</name>
  <sub-locations>
    <location type="state">
      <name>Ohio</name>
      <sub-locations>
        <location type="city"><name>Akron</name></location>
        <location type="city"><name>Columbus</name></location>
      </sub-location>
    </location>
  </sub-locations>
</location>
```

## The many-to-many recursive relationship

Think you\'re getting a feel for recursive relationships yet? Well,
there is still the third and final relationship to add to your
repertoire --- the many-to-many recursive. A common example of a
many-to-many recursive relationship is when one item can be comprised of
many items of the same data type as itself, and each of those sub-items
may belong to another parent item of the same data type. Sound
confusing? Let\'s look at the example of a product that can consist of a
single item or multiple items (i.e., a packaged product). The example
below describes tourist products that can be packaged together to create
a new product.

### product.xsd (XML schema for a many-to-many recursive model)

``` XML
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified">
    <xsd:element name="products">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="product" type="prodType" maxOccurs="unbounded"/>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
    <xsd:complexType name="prodType">
        <xsd:sequence>
            <xsd:element name="prodID" type="xsd:ID"/>
            <xsd:element name="prodName" type="xsd:string"/>
            <xsd:element name="prodCost" type="xsd:decimal" minOccurs="0"/>
            <xsd:element name="prodPrice" type="xsd:decimal"/>
            <xsd:element name="components" type="componentsType" minOccurs="0" maxOccurs="1"/>
        </xsd:sequence>
    </xsd:complexType>
    <xsd:complexType name="componentsType">
        <xsd:sequence>
            <xsd:element name="component" type="xsd:IDREF"/>
            <xsd:element name="componentqty" type="xsd:integer"/>
        </xsd:sequence>
    </xsd:complexType>
</xsd:schema>
```

`<SMALL>`{=html}**Exhibit 5: XML schema for Product
Entity**`</SMALL>`{=html}

### product.xml (XML document for a many-to-many recursive model)

``` XML
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="product.xsl"?>
<products xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="product.xsd">
    <product>
        <prodID>p1000</prodID>
        <prodName>Animal photography kit</prodName>
        <prodPrice>725</prodPrice>
        <components>
            <component>p101</component>
            <componentqty>1</componentqty>
        </components>
    </product>
    <product>
        <prodID>p101</prodID>
        <prodName>Camera case</prodName>
        <prodCost>150</prodCost>
        <prodPrice>300</prodPrice>
    </product>
</products>
```

`<SMALL>`{=html}**Exhibit 6: XML Document for Product
Entity**`</SMALL>`{=html}

## Summary

When the child has the same type of data as its parent in a parent-child
type data relationship, this is a sign of the existence of a recursive
relationship. The `<b>`{=html}xsd:ID`</b>`{=html} and
`<b>`{=html}xsd:IDREF`</b>`{=html} elements can be used in a schema to
create primary key-foreign key values in an XML document.

## Exercises

\

## Answers

**External Links**

-   XML Schema