# XML - Managing Data Exchange/XPath

+----------------------------------------------------------------------+
| `<span style="font-size:large;">`{=html}`<b>`{=html}Learning         |
| objectives`</b>`{=html}`</span>`{=html}                              |
|                                                                      |
| -   `<span style="font-size:medium;">`{=html}Be able to              |
|     conceptualize an XML document as a node tree`</span>`{=html}     |
| -   `<span style="font-size:medium;">`{=html}Refer groups of         |
|     elements in an XML document`</span>`{=html}                      |
| -   `<span style="font-size:medium;">`{=html}Understand the          |
|     differences between abbreviated and unabbreviated XPath          |
|     syntax`</span>`{=html}                                           |
| -   `<span style="font-size:medium;">`{=html}Understand the          |
|     differences between absolute and relative Paths`</span>`{=html}  |
| -   `<span style="font-size:medium;">`{=html}Be able to use XPath    |
|     predicates and functions to refine an XPath\'s                   |
|     node-set`</span>`{=html}                                         |
+----------------------------------------------------------------------+

## Introduction

Throughout the previous chapters you have learned the basic concepts of
XSL and how you must refer to nodes in an XML document when performing
an XSL transformation. Up to this point you have been using a
straightforward syntax for referring to nodes in an XML document.
Although the syntax you have used so far has been XPath there are many
more functions and capabilities that you will learn in this chapter. As
you begin to comprehend how path language is used for referring to nodes
in an XML document your understanding of XML as a tree structure will
begin to fall into place. This chapter contains examples that
demonstrate many of the common uses of XPath, but for the full XPath
specification, see the latest version of the standard at:

<http://www.w3.org/TR/xpath>

XSL uses XPath heavily.

## XPath

When you go to copy a file or 'cd' into a directory at a command prompt
you often type something along the lines of '/home/darnell/' to refer to
folders. This enables you to change into or refer to folders throughout
your computer's file system. XML has a similar way of referring to
elements in an XML document. This special syntax is called XPath, which
is short for XML Path Language.

XPath is a language for finding information in an XML document. XPath is
used to navigate through elements and attributes in an XML document.

XPath, although used for referring to nodes in an XML tree, is not
itself written in XML. This was a wise choice on the part of the W3C,
because trying to specify path information in XML would be a very
cumbersome task. Any characters that form XML syntax would need to be
escaped so that it is not confused with XML when being processed. XPath
is also very succinct, allowing you to call upon nodes in the XML tree
with a great degree of specificity without being unnecessarily verbose.

## XML as a tree structure

The great benefit about XML is that the document itself describes the
structure of data. If any of you have researched your family history,
you have probably come across a family tree. At the top of the tree is
some early ancestor and at the bottom of the tree are the latest
children.

With a tree structure you can see which children belong to which
parents, which grandchildren belong to which grandparents and many other
relationships.

The neat thing about XML is that it also fits nicely into this tree
structure, often referred to as an XML Tree.

## Understanding node relationships

We will use the following example to demonstrate the different node
relationships.

``` xml
<bookstore>
    <book>
        <title>Less Than Zero</title>
        <author>Bret Easton Ellis</author>
        <year>1985</year>
        <price>13.95</price>
    </book>
</bookstore>
```

Parent
:   Each element and attribute has one parent.
:   The book element is the parent of the title, author, year, and
    price:

```{=html}
<!-- -->
```

Children
:   Element nodes may have zero, one or more children.
:   The title, author, year, and price elements are all children of the
    book element:

```{=html}
<!-- -->
```

Siblings
:   Nodes that have the same parent.
:   The title, author, year, and price elements are all siblings:

```{=html}
<!-- -->
```

Ancestors
:   A node\'s parent, parent\'s parent, etc.
:   The ancestors of the title element are the book element and the
    bookstore element:

```{=html}
<!-- -->
```

Descendants
:   A node\'s children, children\'s children, etc.
:   Descendants of the bookstore element are the book, title, author,
    year, and price elements:

Also, it is still useful in some ways to think of an XML file as
simultaneously being a serialized file, like you would view it in an XML
editor. This is so you can understand the concepts of preceding and
following nodes. A node is said to **precede** another if the original
node is before the other in document order. Likewise, a node **follows**
another if it is after that node in document order. Ancestors and
descendants are not considered to be either preceding or following a
node. This concept will come in handy later when discussing the concept
of an axis.

## Abbreviated vs. Unabbreviated XPath syntax

XPath was created so that nodes can be referred to very succinctly,
while retaining the ability to search on many options. Most uses of
XPath will involve searching for child nodes, parent nodes, or attribute
nodes of a particular node. Because these uses are so common, an
abbreviated syntax can be used to refer to these commonly-searched
nodes. Following is an XML document that simulates a tree (the type that
has leaves and branches.) It will be used to demonstrate the different
types of syntax.

``` xml
<?xml version="1.0" encoding="UTF-8"?>
    <trunk name="the_trunk">
        <bigBranch name="bb1" thickness="thick">
            <smallBranch name="sb1">
                <leaf name="leaf1" color="brown" />
        <leaf name="leaf2" weight="50" />
        <leaf name="leaf3" />
        </smallBranch>
        <smallBranch name="sb2">
                <leaf name="leaf4" weight="90" />
        <leaf name="leaf5" color="purple" />
            </smallBranch>
        </bigBranch>
        <bigBranch name="bb2">
            <smallBranch name="sb3">
        <leaf name="leaf6" />
        </smallBranch>
        <smallBranch name="sb4">
        <leaf name="leaf7" />
        <leaf name="leaf8" />
        <leaf name="leaf9" color="black" />
        <leaf name="leaf10" weight="100" />
            </smallBranch>
        </bigBranch>
    </trunk>
```

`<small>`{=html}Exhibit 9.2: tree. xml -- Example XML
page`</small>`{=html}

Following are a few examples of XPath location paths in English,
Abbreviated XPath, then Unabbreviated XPath.

**Selection 1:**

**English:** All \<leaf\> elements in this document that are children of
\<smallBranch\> elements that are children of \<bigBranch\> elements,
that are children of the trunk, which is a child of the root.\
**Abbreviated:** /trunk/bigBranch/smallBranch/leaf\
**Unabbreviated:**
/child::trunk/child::bigBranch/child::smallBranch/child::leaf

**Selection 2:**

**English:** The \<bigBranch\> elements with 'name' attribute equal to
'bb3,' that are children of the trunk element, which is a child of the
root.\
**Abbreviated:** /trunk/bigBranch\[@name='bb3'\]\
**Unabbreviated:**
/child::trunk/child::bigBranch\[attribute::name='bb3'\]

Notice how we can specify which bigBranch objects we want by using a
predicate in the previous example. This narrows the search down to only
bigBranch nodes that satisfy the **predicate**. The predicate is the
part of the XPath statement that is in square brackets. In this case,
the predicate is asking for bigBranch nodes with their 'name' attribute
set to 'bb3'.

The last two examples assume we want to specify the path from the root.
Let's now assume that we are specifying the path from a
`<smallBranch>`{=html} node.

**Selection 3:**

**English:**The parent node of the current \<smallBranch\>. (Notice that
this selection is relative to a \<smallBranch\>)\
**Abbreviated:** ..\
**Unabbreviated:** parent::node()

When using the Unabbreviated Syntax, you may notice that you are calling
a parent or child followed by two colons (::). Each of those are called
an **axis**. You will learn more about axes shortly.

Also, this may be a good time to explain the concept of a **location
path**. A location path is the series of location steps taken to reach
the node/nodes being selected. **Location steps** are the parts of XPath
statements separated by / characters. They are one step on the way to
finding the nodes you would like to select.

Location steps are comprised of three parts: an axis (child, parents,
descendant, etc.), a node test (name of a node, or a function that
retrieves one or more nodes), and a series of predicates (tests on the
retrieved nodes that narrow the results, eliminating nodes that do not
pass the predicate's test).

So, in a location path, each of its location steps returns a node-list.
If there are further steps on the path after a location step, the next
step is executed on all the nodes returned by that step.

## Relative vs. Absolute paths

When specifying a path with XPath, there are times when you will already
be 'in' a node. But other times, you will want to select nodes starting
from the root node. XPath lets you do both. If you have ever worked with
websites in HTML, it works the same way as referring to other files in
HTML hyperlinks. In HTML, you can specify an **Absolute Path** for the
hyperlink, describing where another page is with the server name,
folders, and filename all in the URL. Or, if you are referring to
another file on the same site, you need not enter the server name or all
of the path information. This is called a **Relative Path**. The concept
can be applied similarly in XPath.

You can tell the difference by whether there is a '/' character at the
beginning of the XPath expression. If so, the path is being specified
from the root, which makes it an Absolute Path. But if there is no '/'
at the beginning of the path, you are specifying a Relative Path, which
describes where the other nodes are relative to the **context node**, or
the node for which the next step is being taken.

Below is an XSL stylesheet (Exhibit 9.3) for use with our tree.xml file
above (Exhibit 9.2).

``` xml
<?xml version="1.0" encoding="UTF-8" ?>
 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="html"/>

<!-- Example of an absolute link. The element '/child::trunk'
 is being specified from the root element. -->

 <xsl:template match="/child::trunk">

<html>
    <head>
        <title>XPath Tree Tests</title>
    </head>
     <body>

<!-- Example of a relative link. The <for-each> xsl statement will
    execute for every <bigBranch> node in the
    ‘current’ node, which is the <trunk>node. -->

 <xsl:for-each select="child::bigBranch">

         <xsl:call-template name="print_out" />
           </xsl:for-each>
        </body>
   </html>
</xsl:template>
      <xsl:template name="print_out">
             <xsl:value-of select="attribute::name" /> <br />
   </xsl:template>
 </xsl:stylesheet>
```

`<small>`{=html}Exhibit 9.3: xsl_tree.xsl -- Example of both a relative
and absolute path`</small>`{=html}

## Four types of XPath location paths

In the last two sections you learned about two different distinctions to
separate out different location paths: Unabbreviated vs. Abbreviated and
Relative vs. Absolute. Combining these two concepts could be helpful
when talking about XPath location paths. Not to mention, it could make
you sound really smart in front of your friends when you say things
like:

:#Abbreviated Relative Location Paths- Use of abbreviated syntax while
specifying a relative path.

:#Abbreviated Absolute Location Paths- Use of abbreviated syntax while
specifying a absolute path.

:#Unabbreviated Relative Location Paths- Use of unabbreviated syntax
while specifying a relative path.

:#Unabbreviated Absolute Location Paths- Use of unabbreviated syntax
while specifying a absolute path.

I only mention this four-way distinction now because it could come in
handy while reading the specification, or other texts on the subject.

## XPath axes

In XPath, there are some node selections whose performance requires the
Unabbreviated Syntax. In this case, you will be using an axis to specify
each location step on your way through the location path.

From any node in the tree, there are 13 axes along which you can step.
They are as follows:

  Axes                   Meaning
  ---------------------- ------------------------------------------------------------------------------------
  ancestor::             Parents of the current node up to the root node
  ancestor-or-self::     Parents of the current node up to the root node and the current node
  attribute::            Attributes of the current node
  child::                Immediate children of the current node
  descendant::           Children of the current node (including children\'s children)
  descendant-or-self::   Children of the current node (including children\'s children) and the current node
  following::            Nodes after the current node (excluding children)
  following-sibling::    Nodes after the current node (excluding children) at the same level
  namespace::            XML namespace of the current node
  parent::               Immediate parent of the current node
  preceding::            Nodes before the current node (excluding children)
  preceding-sibling::    Nodes before the current node (excluding children) at the same level
  self::                 The current node

## XPath predicates and functions

Sometimes, you may want to use a predicate in an XPath Location Path to
further filter your selection. Normally, you would get a set of nodes
from a location path. A predicate is a small expression that gets
evaluated for each node in a set of nodes. If the expression evaluates
to 'false', then the node is not included in the selection. An example
is as follows:

//p\[@class='alert'\]

In the preceding example, every \<p\> tag in the document is checked to
see if its 'class' attribute is set to 'alert'. Only those \<p\> tags
with a 'class' attribute with value 'alert' are included in the set of
nodes for this location path.

The following example uses a function, which can be used in a predicate
to get information about the context node.

/book/chapter\[position()=3\]

This previous example selects only the chapter of the book in the third
position. So, for something to be returned, the current \<book\> element
must have at least 3 \<chapter\> elements.

Also notice that the position function returns an integer. There are
many functions in the XPath specification. For a complete list, see the
W3C specification at <http://www.w3.org/TR/xpath#corelib>

Here are a few more functions that may be helpful:

number **last**() -- last node in the current node set

number **position**() -- position of the context node being tested

number **count**(node-set) -- the number of nodes in a node-set

boolean **starts-with**(string, string) -- returns true if the first
argument starts with the second

boolean **contains**(string, string) -- returns true if the first
argument contains the second

number **sum**(node-set) -- the sum of the numeric values of the nodes
in the node-set

number **floor**(number) -- the number, rounded down to the nearest
integer

number **ceiling**(number) -- the number, rounded up to the nearest
integer

number **round**(number) -- the number, rounded to the nearest integer

## Example

The following XML document, XSD schemas, and XSL stylesheet examples are
to help you put everything you have learned in this chapter together
using real life data. As you study this example you will notice how
XPath can be used in the stylesheet to call and modify the output of
specific information from the document.

Below is an XML document (Exhibit 9.4)

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

<movie>
    <movieTitle>Meet the Parents</movieTitle>
    <movieSynopsis>
    Greg Focker is head over heels in love with his girlfriend Pam, and is ready to
    pop the big question. When his attempt to propose is thwarted by a phone call
    with the news that Pam's younger sister is getting married, Greg realizes that
    the key to Pam's hand in marriage lies with her formidable father.
    </movieSynopsis>
    <role>
        <roleIDREF>bs1</roleIDREF>
        <roleType>Lead Actor</roleType>
    </role>
    <role>
        <roleIDREF>tp1</roleIDREF>
        <roleType>Lead Actress</roleType>
    </role>
    <role>
        <roleIDREF>rd1</roleIDREF>
        <roleType>Lead Actor</roleType>
    </role>
    <role>
        <roleIDREF>bd1</roleIDREF>
        <roleType>Supporting Actress</roleType>
    </role>
</movie>

<movie>
    <movieTitle>Elf</movieTitle>
    <movieSynopsis>
    One Christmas Eve, a long time ago, a small baby at an orphanage crawled into
    Santa’s bag of toys, only to go undetected and accidentally carried back to Santa’s
    workshop in the North Pole. Though he was quickly taken under the wing of a surrogate
    father and raised to be an elf, as he grows to be three sizes larger than everyone else,
    it becomes clear that Buddy will never truly fit into the elf world. What he needs is
    to find his real family. This holiday season, Buddy decides to find his true place in the
    world and sets off for New York City to track down his roots.
    </movieSynopsis>
    <role>
        <roleIDREF>wf1</roleIDREF>
        <roleType>Lead Actor</roleType>
    </role>
    <role>
        <roleIDREF>jc1</roleIDREF>
        <roleType>Supporting Actor</roleType>
    </role>
    <role>
        <roleIDREF>zd1</roleIDREF>
        <roleType>Lead Actress</roleType>
    </role>
    <role>
        <roleIDREF>ms1</roleIDREF>
        <roleType>Supporting Actress</roleType>
    </role>
    </movie>

<castMember>
    <castMemberID>rd1</castMemberID>
    <castFirstName>Robert</castFirstName>
    <castLastName>De Niro</castLastName>
    <castSSN>489-32-5984</castSSN>
    <castGender>male</castGender>
</castMember>

<castMember>
    <castMemberID>bs1</castMemberID>
    <castFirstName>Ben</castFirstName>
    <castLastName>Stiller</castLastName>
    <castSSN>590-59-2774</castSSN>
    <castGender>male</castGender>
</castMember>

<castMember>
    <castMemberID>tp1</castMemberID>
    <castFirstName>Teri</castFirstName>
    <castLastName>Polo</castLastName>
    <castSSN>099-37-8765</castSSN>
    <castGender>female</castGender>
</castMember>

<castMember>
    <castMemberID>bd1</castMemberID>
    <castFirstName>Blythe</castFirstName>
    <castLastName>Danner</castLastName>
    <castSSN>273-44-8690</castSSN>
    <castGender>male</castGender>
</castMember>

<castMember>
    <castMemberID>wf1</castMemberID>
    <castFirstName>Will</castFirstName>
    <castLastName>Ferrell</castLastName>
    <castSSN>383-56-2095</castSSN>
    <castGender>male</castGender>
</castMember>

<castMember>
    <castMemberID>jc1</castMemberID>
    <castFirstName>James</castFirstName>
    <castLastName>Caan</castLastName>
    <castSSN>389-49-3029</castSSN>
    <castGender>male</castGender>
</castMember>

<castMember>
    <castMemberID>zd1</castMemberID>
    <castFirstName>Zooey</castFirstName>
    <castLastName>Deschanel</castLastName>
    <castSSN>309-49-4005</castSSN>
    <castGender>female</castGender>
</castMember>

<castMember>
    <castMemberID>ms1</castMemberID>
    <castFirstName>Mary</castFirstName>
    <castLastName>Steenburgen</castLastName>
    <castSSN>988-43-4950</castSSN>
    <castGender>female</castGender>
</castMember>

</movieCollection>
```

`<small>`{=html}Exhibit 9.4: movies_xpath.xml`</small>`{=html}

Below is the second XML document (Exhibit 9.5)

``` xml
<?xml version="1.0" encoding="UTF-8"?>

<cities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="cities.xsd">

<city>
    <cityID>c2</cityID>
    <cityName>Mandal</cityName>
    <cityPopulation>13840</cityPopulation>
    <cityCountry>Norway</cityCountry>
    <tourismDescription>A small town with a big atmosphere.  Mandal provides comfort
away from normal luxuries.
    </tourismDescription>
    <capitalCity>c3</capitalCity>
</city>

<city>
    <cityID>c3</cityID>
    <cityName>Oslo</cityName>
    <cityPopulation>533050</cityPopulation>
    <cityCountry>Norway</cityCountry>
    <tourismDescription>Oslo is the capital of Norway for many reasons.
    It is also the capital location for tourism.  The culture, shopping,
    and attractions can all be experienced in Oslo.  Just remember
    to bring your wallet.
    </tourismDescription>
</city>

</cities>
```

`<small>`{=html}Exhibit 9.5: cites\_\_xpath.xml`</small>`{=html}

Below is the Movies schema (Exhibit 9.6)

``` xml
<?xml version="1.0" encoding="UTF-8"?>

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified">

  <!--Movie Collection-->

  <xsd:element name="movieCollection">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="movie" type="movieDetails" minOccurs="1" maxOccurs="unbounded"/>

      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>

  <!--This contains the movie details.-->

  <xsd:complexType name="movieDetails">
    <xsd:sequence>
      <xsd:element name="movieTitle" type="xsd:string" minOccurs="1" maxOccurs="unbounded"/>
      <xsd:element name="movieSynopsis" type="xsd:string"/>
      <xsd:element name="role" type="roleDetails" minOccurs="1" maxOccurs="unbounded"/>
    </xsd:sequence>
  </xsd:complexType>

 <!--The contains the genre details.-->

  <xsd:complexType name="roleDetails">
    <xsd:sequence>
       <xsd:element name="roleIDREF" type="xsd:IDREF"/>
       <xsd:element name="roleType" type="xsd:string"/>
    </xsd:sequence>
  </xsd:complexType>

  <xsd:simpleType name="ssnType">
       <xsd:restriction base="xsd:string">
           <xsd:pattern value="\d{3}-\d{2}-\d{4}"/>
       </xsd:restriction>
   </xsd:simpleType>

 <xsd:complexType name="castDetails">
    <xsd:sequence>
       <xsd:element name="castMemberID" type="xsd:ID"/>
       <xsd:element name="castFirstName" type="xsd:string"/>
       <xsd:element name="castLastName" type="xsd:string"/>
       <xsd:element name="castSSN" type="ssnType"/>
       <xsd:element name="castGender" type="xsd:string"/>
    </xsd:sequence>
  </xsd:complexType>

</xsd:schema>
```

`<small>`{=html}Exhibit 9.6: movies.xsd`</small>`{=html}

Below is the Cities schema (Exhibit 9.7)

``` 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="cityPopulation" type="xsd:integer"/>
     <xsd:element name="cityCountry" type="xsd:string"/>
     <xsd:element name="tourismDescription" type="xsd:string"/>
     <xsd:element name="capitalCity" type="xsd:IDREF" minOccurs="0" maxOccurs="1"/>
  </xsd:sequence>
</xsd:complexType>
</xsd:schema>
```

`<small>`{=html}Exhibit 9.7: cities.xsd`</small>`{=html}

Below is the XSL stylesheet (Exhibit 9.8)

``` xml
<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:key name="castList" match="castMember" use="castMemberID"/>
<xsl:output method="html"/>

<!-- example of using an abbreviated absolute path to pull info
from cities_xpath.xml for the city "Oslo" specifically -->

<!-- specify absolute path to select cityName and assign it the variable "city" -->
<xsl:variable name="city" select="document('cities_xpath.xml')
/cities/city[cityName='Oslo']/cityName" />

<!-- specify absolute path to select cityCountry and assign it the variable "country" -->
<xsl:variable name="country" select="document('cities_xpath.xml')
/cities/city[cityName='Oslo']/cityCountry" />

<!-- specify absolute path to select tourismDescription and assign it the variable "description" -->
<xsl:variable name="description" select="document('cities_xpath.xml')
/cities/city[cityName='Oslo']/tourismDescription" />

<xsl:template match="/">
<html>
    <head>
        <title>Movie Collection</title>
    </head>
    <body>
        <h2>Movie Collection</h2>
    <xsl:apply-templates select="movieCollection"/>
    </body>
</html>
</xsl:template>
<xsl:template match="movieCollection">

<!-- let's say we just want to see the actors. -->
<!--
<xsl:for-each select="movie">
<hr />
<br />
<b><xsl:text>Movie Title: </xsl:text></b>
<xsl:value-of select="movieTitle"/>
<br />
<br />
<b><xsl:text>Movie Synopsis: </xsl:text></b>
<xsl:value-of select="movieSynopsis"/>
<br />
<br />-->

<!-- actor info begins here. -->
<b><xsl:text>Cast: </xsl:text></b>
<br />
<!-- specify an abbreviated relative path here for "role."
NOTE: there is no predicate in this one; it's just a path. -->

<xsl:for-each select="movie/role">
<xsl:sort select="key('castList',roleIDREF)/castLastName"/>
<xsl:number value="position()" format="
 0. " />
<xsl:value-of select="key('castList',roleIDREF)/castFirstName"/>
<xsl:text>   </xsl:text>
<xsl:value-of select="key('castList',roleIDREF)/castLastName"/>
<xsl:text>,   </xsl:text>
<xsl:value-of select="roleType"/>
<br />
<xsl:value-of select="key('castList',roleIDREF)/castGender"/>
<xsl:text>,   </xsl:text>
<xsl:value-of select="key('castList',roleIDREF)/castSSN"/>
<br />
<br />
</xsl:for-each>
<!--
</xsl:for-each>-->
<hr />

<!--calling the variables -->

<span style="color:red;">
<p><b>Travel Advertisement</b></p>

<!-- reference the city, followed by a comma, and then the country -->
<p><xsl:value-of select="$city" />, <xsl:value-of select="$country" /></p>

<!-- reference the description -->
<xsl:value-of select="$description" />

</span>
</xsl:template>
</xsl:stylesheet>
```

`<small>`{=html}Exhibit 9.6: movies.xsl`</small>`{=html}

## Summary

  ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  Throughout the chapter we have learned many of the features and capabilities of the XML Path Language. You should now have a good understanding of node relationships though the use of the XML tree structure. Using the concept of Abbreviated and Unabbreviated location paths allows us to narrow our searches down to only a particular element by satisfying the predicate in the square brackets. Relative and Absolute are used for specifying the path to your location. The Relative path gives the file location in relation to the current working directory while the Absolute path gives an exact location of a file or directory name within a computer or file system. Both of these concepts can be combined to come up with four types of XPath location paths: Abbreviated Relative, Abbreviated Absolute, Unabbreviated Relative, and lastly Unabbreviated Absolute. If further filtering is required XPath predicates and functions can be used. These allow for the predicate to be evaluated for such things as true/false and count functions. When used correctly XPath can be a very powerful tool in the XML language.
  ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

## Exercises

## Answers

fr:Programmation XML/XPath
it:XML/XPath


# XML - Managing Data Exchange/XLink

```{=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
    XLink\'s in XML`</font>`{=html}
-   `<font size=3>`{=html} create a custom XLink`</font>`{=html}
-   `<font size=3>`{=html} learn the functionality behind various XLink
    parameters`</font>`{=html}

```{=html}
</td>
```
```{=html}
<td>
```
sponsored by:\
\

```{=html}
<center>
```
`<font size=3>`{=html}`<b>`{=html}The University of
Georgia`</b>`{=html}`</font>`{=html}\
\
`<font size=5 color=#990000>`{=html}`<b>`{=html}Terry College of
Business`</b>`{=html}`</font>`{=html}\
\
`<font size=3>`{=html}`<b>`{=html}Department of Management Information
Systems`</b>`{=html}`</font>`{=html}

```{=html}
</center>
```
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
\
\
==Introduction== Through the use of Uniform Resource Identifiers
(URI\'s), an **XLink** allows elements to be inserted into XML documents
that create links between resources such as documents, images, files and
other pages. An XLink is similar in concept to an HTML hyperlink, but is
more powerful and flexible.

This chapter will be a general overview of the XLink syntax. It will
also provide exposure to some of XLink\'s basic concepts. For the full
XLink specification, see the latest version of the standard at:

<http://www.w3.org/TR/xlink>

## XLink

XLinks create a linking relationship between two or more resources. They
allow for any XML element, image, text or markup files to be specified
in the link.

By using a method similar to the centralized formatting of XSL
stylesheets, XLinks allow a document\'s hyperlinks to be isolated and
centralized in a separate document. As a linked document\'s addresses
changes, the XLink remains functional.

The use of XLink requires the declaration of the XLink
namespace. This namespace provides the
global attributes for type, href, role, arcrole, title, show, actuate,
label, from and to. The following example would make the prefix xlink
available within the tourGuide element.

``` xml
<tourGuide
  xmlns:xlink="http://www.w3.org/1999/xlink">
  ...
</tourGuide>
```

## XLink global attributes

The following table outlines the attributes that can be used with the
xlink namespace. The global attributes are type, href, role, arcrole,
title, show, actuate, label, from, and to. The table also includes
descriptions of how the attributes can be used.

**Exhibit 1: Table of global attributes**\

```{=html}
<table cellspacing=10 cellpadding=10 border=5>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<font size=3>`{=html}`<b>`{=html}Attributes`</b>`{=html}`</font>`{=html}

```{=html}
</td>
```
```{=html}
<td>
```
`<font size=3>`{=html}`<b>`{=html}Description and Valid
Values`</b>`{=html}`</font>`{=html}

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

```{=html}
</td>
```
```{=html}
<td>
```
Describes the meaning of an item\

-   simple - basic format similar to html linkage
-   extended - more complex than simple types with multi functional
    format
-   resource - provides local resources
-   locator - provides remote resources
-   arc - provides the ability to traverse from one resource to another
-   title - readable name or explanation of link

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

```{=html}
</td>
```
```{=html}
<td>
```
Location of resource\

-   value is URI

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

```{=html}
</td>
```
```{=html}
<td>
```
Description of XLink\'s content\

-   value is URI
-   describes the element whose role it is

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

```{=html}
</td>
```
```{=html}
<td>
```
Description of XLink\'s content\

-   value is URI
-   describe the relationship between the two sides of the arc

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

```{=html}
</td>
```
```{=html}
<td>
```
Name displayed, usually short description of link\

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

```{=html}
</td>
```
```{=html}
<td>
```
Describes behavior of the browser once the XLink has been actuated and
loaded\

-   new - load in a new window or frame
-   replace - load in same window or frame
-   embed - replace the current item
-   other - look for information elsewhere
-   none - not specified

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

```{=html}
</td>
```
```{=html}
<td>
```
Specifies when resource is retrieved or link processing occurs\

-   onRequest - when user requests the link
-   onLoad - when page is loaded
-   other - looks for information elsewhere
-   none - not specified

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}label, from & to`</b>`{=html}

```{=html}
</td>
```
```{=html}
<td>
```
Specifies link direction

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

## XML schema

\
The following XML schema defines a tour guide that contains at least one
city. Each city contains one or more attractions. The name of each
attraction is an XLink.

**Exhibit 2: XML schema for TourGuide**

``` xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
      Document   : TourGuide.xsd
      Created on : February 28, 2006
      Author     : Billy Timmins
-->
<!--
      Declaration of usage of xlink Namespace
-->
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified"
            xmlns:xlink="http://www.w3.org/1999/xlink">
    <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 section 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"/>
           <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="description" type="xsd:string"/>
            <xsd:element name="attraction" type="attractionDetails" minOccurs="1" maxOccurs="unbounded"/>
         </xsd:sequence>
     </xsd:complexType>
     <xsd:complexType name="attractionDetails">
         <xsd:sequence>
         <!--
         Note use of xlink
         -->
            <xsd:element name="attractionName" xlink:type="simple"/>
            <xsd:element name="attractionDescription" type="xsd:string"/>
            <xsd:element name="attractionRating" type="xsd:integer"/>
        </xsd:sequence>
     </xsd:complexType>
</xsd:schema>
```

## XML document

\
The following XML document shows how the XLink, attractionName, defined
in the XML schema, is used in an XML document. Note that it is necessary
to include xlink:href=\"\" within the attribute tags in order to define
the linked website.

**Exhibit 3: XML document for TourGuide.xsd (using XLink)**

``` xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
      Document   : SomeTourGuide.xml
      Created on : February 28, 2006
      Author     : Billy Timmins
-->
<!--
      Declaration of usage of XLink Namespace
-->
<?xml-stylesheet href="TourGuide.xsl" type="text/xsl"?>
<tourGuide xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xlink="http://www.w3.org/1999/xlink" xsi:noNamespaceSchemaLocation="TourGuide.xsd">
    <city>
        <cityName>Atlanta</cityName>
        <adminUnit>Georgia</adminUnit>
        <country>USA</country>
        <continent>North America</continent>
        <population>425000</population>
        <description>Atlanta is the capital of and largest city in the U.S. state of Georgia.</description>
        <attraction>
            <!--
            Declaration of XLink and associated link
            -->
            <attractionName xlink:href="http://www.georgiaaquarium.org/"> Georgia Aquarium </attractionName>
            <attractionDescription>World’s Largest Aquarium</attractionDescription>
            <attractionRating>5</attractionRating>
        </attraction>
        <attraction>
            <!--
            Declaration of XLink and associated link
            -->
            <attractionName xlink:href="http://www.high.org/"> High Museum of Art </attractionName>
            <attractionDescription>The High Museum of Art, founded in 1905 as the Atlanta Art Association, is the leading art museum in the Southeastern United States.</attractionDescription>
            <attractionRating>4</attractionRating>
        </attraction>
        <attraction>
            <!--
            Declaration of XLink and associated link
            -->
            <attractionName xlink:href="http://www.underground-atlanta.com/"> Underground Atlanta </attractionName>
            <attractionDescription> Go beneath the streets of a bustling downtown, to the heart of a great American city.  Underground Atlanta is at the center of it all.</attractionDescription>
            <attractionRating>2</attractionRating>
        </attraction>
    </city>
    <city>
        <cityName>Tampa</cityName>
        <adminUnit>Florida</adminUnit>
        <country>USA</country>
        <continent>North America</continent>
        <population>303000</population>
        <description>Tampa is a major United States city located in Hillsborough County, on the west coast of Florida.</description>
        <attraction>
            <!--
            Declaration of XLink and associated link
            -->
            <attractionName xlink:href="http://www.buschgardens.com/buschgardens/fla/default.aspx"> Bush Gardens </attractionName>
            <attractionDescription>The nation's fourth largest zoo, Bush Gardens is where you can see African animals roaming free and an exciting amusement park featuring its world-famous rides like Kumba and the new inverted roller-coaster, Montu.</attractionDescription>
            <attractionRating>5</attractionRating>
        </attraction>
        <attraction>
            <!--
            Declaration of XLink and associated link
            -->
            <attractionName xlink:href="http://www.plantmuseum.com/"> Henry B. Plant Museum </attractionName>
            <attractionDescription>Discover a museum which transports you to turn-of-the-century Florida.</attractionDescription>
            <attractionRating>1</attractionRating>
        </attraction>
    </city>
</tourGuide>
```

## XML stylesheet

\
The following XML stylesheet displays the contents of the XML document.

**Exhibit 4: XML stylesheet TourGuide**

``` xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
      Document   : TourGuide.xsl
      Created on : February 28, 2006
      Author     : Billy Timmins
-->
<!--
      Declaration of usage of XLink Namespace
-->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xlink="http://www.w3.org/1999/xlink" exclude-result-prefixes="xlink" version="1.0">
    <xsl:output method="html"/>
    <!--
    Attribute XLink defined as an href of simple type
    -->
    <xsl:template match="*[@xlink:type = 'simple' and @xlink:href]">
        <a href="{@xlink:href}">
            <xsl:apply-templates/>
        </a>
    </xsl:template>
    <xsl:template match="/">
        <html>
            <head>
                <title>Tour Guide XLink Example</title>
            </head>
            <body>
                <h2>Cities</h2>
                <xsl:apply-templates select="tourGuide"/>
            </body>
        </html>
    </xsl:template>
    <!--
    template for handling a link
    -->
    <xsl:template match="attractionName">
        <a href="{@xlink:href}">
            <xsl:value-of select="."/>
        </a>
    </xsl:template>
    <xsl:template match="tourGuide">
        <table border="1" width="100%">
            <xsl:for-each select="city">
                <tr>
                    <td>
                        <br/>
                        <xsl:text>City: </xsl:text>
                        <xsl:value-of select="cityName"/>
                        <br/>
                        <xsl:text>County: </xsl:text>
                        <xsl:value-of select="adminUnit"/>
                        <br/>
                        <xsl:text>Continent: </xsl:text>
                        <xsl:value-of select="continent"/>
                        <br/>
                        <xsl:text>Population: </xsl:text>
                        <xsl:value-of select="population"/>
                        <br/>
                        <xsl:text>Description: </xsl:text>
                        <xsl:value-of select="description"/>
                        <br/>
                        <br/>
                    </td>
                </tr>
                <tr>
                    <td>
                        <xsl:text>Attraction: </xsl:text>
                    </td>
                    <td>
                        <xsl:text>Attraction Description: </xsl:text>
                    </td>
                    <td>
                        <xsl:text>Attraction Rating: </xsl:text>
                    </td>
                </tr>
                <xsl:for-each select="attraction">
                    <tr>
                        <td>
                            <!--
                            application of the template
                            -->
                            <xsl:apply-templates select="attractionName"/>
                        </td>
                        <td>
                            <xsl:value-of select="attractionDescription"/>
                        </td>
                        <td>
                            <xsl:value-of select="attractionRating"/>
                        </td>
                    </tr>
                </xsl:for-each>
            </xsl:for-each>
        </table>
    </xsl:template>
</xsl:stylesheet>
```

## Summary

  --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  XLink is an extremely versatile specification that standardizes the process for linking to other data sources. Not only does XLink support unidirectional linking similar to an anchor tag in HTML but also can be used to create bidirectional links. Additionally, XLink allows for the linkage from any XML element. This gives great freedom to the developer.
  --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

## Exercises

## Answers


# XML - Managing Data Exchange/CSS

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

## Learning objectives

Upon completion of this chapter, for CSS you will be able to

-   know the benefits of using CSS
-   know the limitations of CSS, so you are able to find the best
    solution for your document
-   know how to implement and use CSS on an XML document

## Introduction

CSS (Cascading Style Sheets) is a language that describes the
presentation form of a structured document.

An XML or an HTML based document does not have a set style, but it
consists of structured text without style information. How the document
will look when printed on paper and viewed in a browser or maybe a
cellphone is determined by a style sheet. A good way of making a
document look consistent and easy to update is by using CSS, which
Wikipedia is a good example of.

## History of CSS

Style sheets have been around in one form or another since the
beginnings of HTML in the early 1990s. Various browsers included their
own style language which could be used to customize the appearance of
web documents. Originally, style sheets were targeted towards the
end-user; early revisions of HTML did not provide many facilities for
presentational attributes, so it was often up to the user to decide how
web documents would appear.

As the HTML language grew, however, it came to encompass a wider variety
of stylistic capabilities to meet the demands of web developers. With
these capabilities, style sheets became less important, and an external
language for the purposes of defining style attributes was not widely
accepted until the development of CSS.

The concept of Cascading Style Sheets was originally proposed in 1994 by
Håkon Wium Lie. Bert
Bos was at the time working on a
browser called Argo which used its own style sheets; the two decided to
work together to develop CSS.

A number of other style sheet languages had already been proposed, but
CSS was the first to incorporate the idea of \"cascading\" \-- the
capability for a document\'s style to be inherited from more than one
\"style sheet.\" This permitted a user\'s preferred style to override
the site author\'s specified style in some areas, while inheriting, or
\"cascading\" the author\'s style in other areas. The capability to
cascade in this way permits both users and site authors added
flexibility and control; it permitted a mixture of stylistic
preferences.

Håkon\'s proposal was presented at the \"Mosaic and the Web\" conference
in Chicago in 1994, and again with Bert Bos in 1995. Around this time,
the World Wide Web Consortium was being established; the W3C took an
interest in the development of CSS, and organized a workshop toward that
end. Håkon and Bert were the primary technical staff on the project,
with additional members, including Thomas Reardon of Microsoft,
participating as well. By the end of 1996, CSS was nearly ready to
become official. The CSS level 1 Recommendation was published in
December 1996.

Early in 1997, CSS was assigned its own working group within the W3C.
The group began tackling issues that had not been addressed with CSS
level 1, resulting in the creation of CSS level 2, which was published
as an official Recommendation in May 1998. CSS level 3 is still under
development as of 2005.

## Why use CSS?

### Cleaner Looking Code

A mass of HTML tags which manage design elements generally obscure the
content of a page, making the code harder to read and maintain. Using
CSS, the content of the page is separated from the design, making
content production in formats such as HTML, XHTML, and XML as easy as
possible.

### Pages Will Load Faster

Non-CSS design typically consists of more code than a CSS-designed
website.

In a non-CSS design, the information about the design is reloaded every
time a visitor accesses a new page. Additionally, the finer points of
design are executed awkwardly. For example, a common method of defining
the spacing of a web page is to use blank GIF images inside tables.

Using CSS keeps content and design separated, so much less code will be
needed. The CSS file loads only once per session, and is saved locally
in the user\'s cache. All information about dimensions is defined in
this stylesheet, rendering awkward constructions like blank GIF images
unnecessary.

Although an increasing amount of Internet users have broadband, the size
of a web page can be important to users who are limited to dial-up
connections. Suppose a dial-up user accesses a company\'s website, and
this visitor experiences lengthy loading times. It is quite possible
that the visitor would stop their visit or form an opinion of this
company as \"slow.\" In this way, a seemingly small difference could
mean added revenue.

Furthermore, bandwidth is not free and most webhosting firms limit the
amount used. In fact, many hosts charge based on bandwidth usage, so
less code could also reduce costs.

### Redesign Becomes Trivial

When used properly, CSS is a very powerful tool that gives a web
architect complete control over a site\'s presentation. It is a notation
in which the rules of a design are governed. This becomes very useful
for a large website which requires a consistent appearance for every
type of element (such as a title, a subtitle, a piece of code, or a
paragraph).

For example, suppose a company has a 1,200 page website which took many
months to complete. The company then undergoes a rebranding and thus the
font, the background, the style of hyperlinks, and so forth needs to be
updated with the new corporate design. If the site was engineered
properly using CSS, this change would be as simple as editing the
appropriate lines of a single CSS file (assuming it is an external
stylesheet). If CSS is not used, the code that manages the appearance is
stored in each of the pages. In order to update the design in this case,
each file would have to be updated *individually*.

### Graceful Degradation

{{\...}}

### Accessibility

People with lowered vision or users with special web browsers, e.g.
people that are blind, will probably like a CSS designed website better
than one not designed using CSS. Because CSS allows you to define the
reading order separately from the visual layout it makes it easier for
the special web browsers to read the page. Bear in mind that anyone who
wears glasses or contact lenses can be considered to have lower vision.

Many designers lock the font size in pixels which prevents the user
changing the font size. Good CSS design allows the user to increase or
decrease the font size at will making pages more usable. A significant
number of web surfers like to use a magnification of 300% or more.

Giving the user the opportunity to change the font size will not make
any difference for the normal user, but it can make a difference for
people that have lowered vision. Ask yourself the question: who is the
website made for? The visitors or the designer?

Websites designed with CSS tend to display better than table-based
designs in the web browsers used in PDAs and cellphones. The use of
cellphones for browsing will probably continue to increase. A
table-based design will make web pages inaccessible to these users.

Be careful with your CSS designs. Misuse of absolute positioning and
absolute rather than relative sizes can make your webpages less
accessible rather than more accessible. A good table design is better
than a bad CSS design.

### Better results in search engines

Extensive use of tables confuses the search engines, they can actually
get problems separating content from code. The search engine robots
start reading on the top of the page, and they want to find out how
relevant the webpage is as fast as possible. Again, less code will make
it easier for the search engines to find code that\'s relevant, and it
will probably give your webpage a better ranking.

## Disadvantages of CSS

The use of CSS for styling has few disadvantages. However some browsers,
especially older ones, will sometimes present the page incorrectly. When
I was gathering information for this chapter it became clear to me that
many experts think that formatting XML with CSS is not the future of the
web. The main view is that XSL will be the new standard. So make sure
you read through the previous chapter of this book one more time. The
formatting parts of XSL and CSS will be quite similar. For example, you
will be able to use all CSS1 and CSS2 properties and values in XSL with
the same meaning as in CSS.

## CSS levels

The first CSS specification to become an official W3C Recommendation is
CSS level 1, published in December 1996. Among its capabilities is
support for:

-   Typeface\|Font properties such as typeface and emphasis
-   Color of text, backgrounds, and other elements
-   Text attributes such as spacing between words, letters, and lines of
    text
-   alignment (typesetting)\|Alignment of text, images, tables and other
    elements
-   Margin, border, padding, and positioning for most elements
-   Unique identification and generic classification of groups of
    attributes

The W3C maintains the CSS1
Recommendation.

CSS level 2 was developed by the W3C and published as a Recommendation
in May 1998. A superset of CSS1, CSS2 includes a number of new
capabilities, among them the absolute, relative, and fixed positioning
of elements, the concept of media types, support for aural style sheets
and bidirectional text, and new font properties such as shadows. The W3C
maintains the CSS2 Recommendation.

CSS level 2 revision 1 or CSS 2.1 fixes errors in CSS2, removes
poorly-supported features and adds already-implemented browser
extensions to the specification. It\'s currently a Candidate
Recommendation.

CSS level 3 is currently under development. The W3C maintains a CSS3
progress report.

## CSS Syntax and Properties

-   The section on selectors has moved to CSS
    Programming/Selectors.
-   The section on color has moved to CSS
    Programming/Color.
-   The section on text has moved to CSS Programming/Fonts and
    Text.
-   The section on borders has moved to CSS Programming/Box
    Model.
-   The section on positioning has moved to CSS
    Programming/Positioning.

The following section contains a list of some of the most common CSS
properties. A complete list can be found
here. The
syntax for the use of CSS in an XML document is the same as that for
HTML. The difference is in how you link your CSS file to the XML
document. To do this you have to write `<code>`{=html}

```{=html}
<?xml-stylesheet href="''X.css''" type="text/css"?>
```
`</code>`{=html} before the root element of your XML document, where
*X.css* of course is the name of the CSS file.

As mentioned earlier in this chapter, CSS is a set of rules that
determines how elements in a document will be shown. The rule has two
parts: a selector and a group of one or more declarations surrounded by
braces (curly brackets):

:

    :   selector { declaration; \...}

The selector is normally the tag you wish to style. Here is an example
of a simple rule containing a single declaration:\
::h1 { color: red; } Result: All h1-elements in the document are shown
with the text color red.

### The general syntax

Rules are usually defined like this:

:

    :   selector { declaration; \...}

The declaration is formed like this:

:

    :   property: value;

Remember that there can be several declarations in one rule. A common
mistake is to mix up colons, which separate the property and value of a
declaration, and semicolons, which separate declarations. A selector
chooses the elements for which the rule applies and the declaration sets
the value for the different properties of the elements that are chosen.

Back to our example:

:

    :   h1 { color: red; }

In our example:

:

    :   selector is the element h1
    :   declaration color: red

The property *color* gets the value *red*

Multiple declarations can be written either on a single line or over
several lines, because whitespace collapses:

:

    :   h1 { color:red; background-color:white; }

or

:

    :   h1 {

        :

            :   color:red;
            :   background-color:white;
    :   }

Details of the properties defined by CSS can be found at CSS
Programming#CSS1
Properties.

## Summary

**Cascading Style Sheets** (CSS), are used with webpages to define the
view of information saved in HTML or XML. While XML and HTML create and
preserve a documents structure, CSS is used to define the appearance and
placement of objects within the document as well as its content. All of
this information is saved in a separate file, the .css file. In the CSS
file are textsize, background color, text types, e.g defined. The
placement of pictures and other animations are also defined in the css
file. If CSS is used correctly it would make a webpage a lot easier to
create and even more important, to maintain. Because you will only have
to make changes in the css file to make the whole website change.

!CSS Zen Garden without
CSS{width="200"}

!Zen Garden with
CSS{width="200"}

\

## References and useful links

-   CSS Property Reference

**References:**\
\* <http://no.wikipedia.org/> - The Norwegian version of Wiki\
\* <http://en.wikipedia.org/wiki/Cascading_Style_Sheets>\
**Useful links:**\
\* W3C has a CSS validator, located at
<http://jigsaw.w3.org/css-validator/>

-   w3cs pages about css
-   HTMLDog CSS Beginners
    Guide
-   CSS Zen Garden \-- See whats possible
    with CSS
-   Cascading Style Sheet
    References
    \-- L. Carlson, University of Minnesota Duluth.
-   Web Design
    Update -
    A a plain text email digest newsletter. It typically goes out once a
    week and has a section on CSS. All web designers and developers are
    invited to join.
-   - Cascading Style Sheets
    Books

## Exercises

### Exercise 1

Using the CSS file provided below, create a price list for books as an
XML document.

```{=html}
<?xml version="1.0"?>
```
Exercise1.css:

    <book> Lord of the rings</book> book{
      display: block;
      background-color: transparent;
      margin: 20px 10px 10px 200px;
    }
    <isbn>1.000.56439 </isbn> isbn{
      display: block;
      font: 12pt/15pt georgia, serif;
    }
    <title> The Two Towers </title> title {
      display: block;
      font: 14pt/18pt verdana, sans-serif;
    }
    <author> J.R.R. Tolkien </author> author {
      display: block;
      font: italic 12pt/15pt georgia, serif;
    }
    <publisher> Penguin </author> author {
      display: block;
      font: 12pt/15pt georgia, serif;
    }
    <price> 48 EUR </price> price{
      display: block;
      font: bold 12pt/15pt georgia, serif;
      color: #ff0000;
      background-color: transparent;
    }

### Exercise 2

Create a personal homepage, where you introduce yourself.

The page should contain one header, one footer, and navigation as a list
of links.

### Solutions

Solutions

### CSS Challenges

Copy and paste the HTML, then take up the challenge to create a
stylesheet to match the picture!


# XML - Managing Data Exchange/Cocoon

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

```{=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} Understand the function of
    Cocoon`</font>`{=html}
-   `<font size=3>`{=html} Create a working sitemap`</font>`{=html}
-   `<font size=3>`{=html} Make available a stylesheet-formatted XML
    document`</font>`{=html}
-   `<font size=3>`{=html} Create a simple Cocoon form`</font>`{=html}
-   `<font size=3>`{=html} Create a simple XSP`</font>`{=html}

```{=html}
</td>
```
```{=html}
<td>
```
sponsored by:\
\

```{=html}
<center>
```
`<font size=3>`{=html}`<b>`{=html}The University of
Georgia`</b>`{=html}`</font>`{=html}\
\
`<font size=5 color=#990000>`{=html}`<b>`{=html}Terry College of
Business`</b>`{=html}`</font>`{=html}\
\
`<font size=3>`{=html}`<b>`{=html}Department of Management Information
Systems`</b>`{=html}`</font>`{=html}

```{=html}
</center>
```
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
\
\

## Introduction

Cocoon is a product of the Apache Software Foundation. It is a powerful
server heavily based on Java and XML technology. While it does have a
command line interface, most users will be able to do everything they
need to with it simply through careful editing of a few configuration
files, formatted as XML documents. If you want to see some examples of
what Cocoon can do, go to <http://MIST5730.terry.uga.edu:8080/cocoon/>.

## Assumptions

This tutorial is set up based on the user having access to an
installation of Cocoon on Terry's Blaze server. If you do not have this
access, simply replace file locations and access methods with those
provided by your server administrator. Some programs described may be
Windows-only; you will need to find out a suitable replacement if you
are a Macintosh or Linux user, although these utilities are often
included with the operating system. JEdit is a free text editor that can
read and save files on an FTP or SFTP server as easily as on a hard
disk, and properly manipulate many different types of files, with the
proper plugins. It is available for Windows, Macintosh, some Linux
distributions and as a platform-independent Java application at
<http://www.jedit.org/>.

## The Sitemap

The primary Cocoon file to be concerned with is sitemap.xmap, located in
the root Cocoon directory. It uses XML tags to define things such as
different ways to present data, the location of important files,
identification of browsers, and the most important aspect, pipelines.
The default xmap will be fine for our purposes, and we will only need to
look at the last few lines of it, where pipeline matches are defined.
This section begins at the tag `<map:pipeline>`{=html}. A pipeline match
looks like this:

``` XML
<map:match pattern=”test”>
    <map:generate type=”file” src=”content/test.xml”/>
    <map:transform type=”xslt” src=”stylesheets/test.xslt”/>
    <map:serialize type=”html”/>
</map:match>
```

Let's look at what each line does. The first line tells Cocoon to watch
for someone browsing to
<http://blaze.terry.uga.edu:8080/cocoon/otc/test>. When this happens,
the actions on the next three lines take place. Cocoon will take the
information from the file test.xml within the content directory, and
apply the stylesheet test.xslt from the stylesheets directory. It
formats this result as an html page, as specified on the fourth line.
Cocoon can use different serializers to format data as an html or xhtml
page, flash object, pdf, or even OpenOffice document. Unlike when
working with XML for other purposes, no XSD schema is needed -- simply
create and populate fields in the XML file as necessary.

## Cocoon Forms

Cocoon forms, or CForms, are a way to use XML structure to create
validating form field objects and then arrange them in a template for
use. The primary advantage of CForms over using HTML forms is that
fields can be validated either with built-in functionality or simple XML
attributes. There are several elements required for this. A definition
XML file, which holds the fields, called \"widgets\":

``` XML
<fd:field id="email" required="true">
<fd:label>Email address:</fd:label>
<fd:datatype base="string"/>
<fd:validation>
<fd:email/>
</fd:validation>
</fd:field>
```

\
A template XML file calls on these widgets, adding HTML code to help
with look and feel:

``` html4strict
<br/>
<ft:widget-label id="email"/>
<ft:widget id="email"/>
```

A Javascript file that controls the flow of data from one file to the
next:

``` javascript
function registration() {
var form = new Form("registration_definition.xml");
form.showForm("registration-display-pipeline");
var viewData = { "username" : form.getChild("name").getValue() }
cocoon.sendPage("registration-success-pipeline", viewData);
}
```

Pipelines in the sitemap that also control flow:

``` XML
<map:match pattern="registration">
<map:call function="registration"/>
</map:match>
...
<map:match pattern="registration-display-pipeline">
<map:generate type="jx" src="registration_template.xml"/>
<map:transform type="i18n">
<map:parameter name="locale" value="en-US"/>
</map:transform>
<map:transform src="forms-samples-styling.xsl"/>
<map:serialize/>
</map:match>
...
<map:match pattern="registration-success-pipeline">
<map:generate type="jx" src="registration_success.jx"/>
<map:serialize/>
</map:match>
```

An XSP can be used in this flow in order to pass submissions to a
database.

## XSPs

XSPs function similarly to JSPs and servlets - they are server-side
applications that can support many users at once. Unlike JSPs and
servlets, XSPs can use XML tags to accomplish much of their
functionality, although they can also use Java code between
`<xsp:logic>`{=html}`</xsp:logic>`{=html} tags. One good use for XSPs is
passing information to a database or recalling and displaying stored
data. While JSPs and servlets have to either call a specific database
connector or contain all of the code for connecting within them, Cocoon
has a configuration file which holds this information, and XSPs just
call the name of the database as specified in WEB-INF/cocoon.xconf:

`<esql:pool>`{=html}`dbname``</esql:pool>`{=html}

XSP code to enter data from a form might look like this:

`  ``<esql:execute-query>`{=html}\
`  ``<esql:query>`{=html}\
`  ``INSERT into otc_users (name,email,password,age,spam) values ('``<xsp:expr>`{=html}`esc_name``</xsp:expr>`{=html}`','``<xsp-request:get-parameter name="email"/>`{=html}`','``<xsp-request:get-parameter name="password"/>`{=html}`','``<xsp-request:get-parameter name="age"/>`{=html}`','``<xsp-request:get-parameter name="spam"/>`{=html}`')`\
`  ``</esql:query>`{=html}\
`  ``</esql:execute-query>`{=html}

## Exercises

1.  Create a basic XML file and accompanying html stylesheet. Upload
    them into the proper folders (content and stylesheets respectively)
    on the Blaze server, and write a pipeline match that would enable
    you to view the XML content with your stylesheet applied in a
    browser. Files and match pattern should be named after your own
    name, for example Bob Jones would use "bjones." It is not necessary
    to upload the pipeline code - simply browse to
    <http://blaze.terry.uga.edu:8080/cocoon/otc/yourname> and it should
    be visible.
2.  Follow along with the CForms example located at
    <http://cocoon.apache.org/2.1/userdocs/basics/sample.html>. Create
    and implement at least one widget of your own making. You can view
    this at work by browsing to
    <http://blaze.terry.uga.edu:8080/cocoon/cforms/registration>.
3.  Browse to opt/tomcat5/webapps/cocoon/cforms on Blaze. Examine
    sitemap-modified.xmap to see how the pipelines could be modified to
    pass CForm data to an XSP. Test.xsp shows how that data could be
    inserted into or called from a database.

## Appendix - Accessing the Blaze server

When you have an account set up on the Blaze server, there are several
steps you will need to take in order to be able to work with files in
the Cocoon directory. Generally, new user accounts are set up with the
user's UGA MyId as the username, and social security number as the
password. This password must be changed at the user's first login, which
requires using an SSH client to accomplish. UGA students can download
Secure Shell Utilities 3.1 at <http://sitesoft.uga.edu/>. Two programs
are installed by this download, Secure Shell Client and Secure File
Transfer Client.

Open the Secure Shell client and click the "Quick Connect" button
located near the top of the window. In the resulting window, enter
"blaze.terry.uga.edu" as the Host Name, and your specified username as
User Name. Port Number should be set to "22", and Authentication Method
should be "Passworded". Click "Connect". In the resulting window, enter
your given password and click "Ok". You may see a window asking to save
the new host key, click "Yes". You will now be presented with a text
box. It will notify you that your password has expired and must be
changed. You will need to enter your given password once, hit enter,
enter your desired new password, hit enter, and again enter your desired
new password and hit enter. Be aware that nothing you type will show up
for security purposes, and you will not be able to delete any typos -
you\'ll have to log in and start over if you mess up. This is all we
will be using the Secure Shell Client application for; you can click the
"Disconnect" button in the row of small buttons at the top of the
screen, and then exit the program.

In order to actually access files on the Blaze server, the Secure File
Transfer Client is used. Open it and click the "Quick Connect" button
located near the top of the window, entering the same Host Name as with
the Secure Shell Client, your new password, and make sure the other
settings are the same. Click "Connect." You will be presented with a
Windows Explorer-type screen where you can browse through the files on
the Blaze server. To access our Cocoon installation go to the "opt"
folder, then the "tomcat5" folder, then the "webapps" folder, then the
cocoon folder. Most of our work will be done in the "otc" folder within.
To download a file for editing, simply highlight it and click the
"Download" button in the row of small buttons at the top of the screen.
Once you select a download location and click "Download." You can then
open it in your editor of choice. To upload a file to the server, simply
do the reverse -- click the "Upload" button in the row of small buttons
as the top of the screen, select a file to upload, and click "Upload,"
which will put the file in the folder you are currently viewing on the
Blaze server.


# XML - Managing Data Exchange/Parsing XML files

+----------------------------------------------------------------------+
| `<font size=4>`{=html}`<b>`{=html}Learning                           |
| objectives`</b>`{=html}`</font>`{=html}\                             |
|                                                                      |
| -   `<font size=3>`{=html}Understand the concept of parsing XML      |
|     files`</font>`{=html}                                            |
| -   `<font size=3>`{=html}Use different APIs for processing XML      |
|     files `</font>`{=html}                                           |
| -   `<font size=3>`{=html}Be aware of the differences between        |
|     different approaches for parsing XML files `</font>`{=html}      |
| -   `<font size=3>`{=html}Decide when to use a particular            |
|     technique`</font>`{=html}                                        |
+----------------------------------------------------------------------+

In the earlier chapters we were taught how to create XML
files in
detail. This involved the development of XML
documents, Style
sheets and
Schema and their validation.
In this chapter, we will focus on different approaches for parsing XML
files and
when to use them.

But first, it is time to refresh what we have learned about parsing.

## The Process of Parsing XML files

One goal of the XML format was to enhance raw data formats like plain
text by including detailed descriptions of the meaning of the content.
Now, in order to be able to read XML files, we use a parser which
basically exposes the document's content through a so-called API
(application programming interface). In other words, a client
application accesses the content of the XML document through an
interface, instead of having to interpret the XML code on its own!

### Simple Text Parsing

One way to extract data from an XML document is simple text parsing --
browsing all characters in the document and check for a desired pattern:

``` XML
<house>
<value><int>150,000</int></value>
</house>
```

Let's say we are interested in the value of the house. Using straight
text parsing, we would scan the file for the character sequence
<int> and call it the start pattern. Then, we
would further scan the document for the end pattern (i.e.
</int></value>). Finally, we
declare the text string in between these two patterns to be the value of
the surrounding <house>...</house> tag.

### Why it doesn\'t work that way

Obviously, this approach is not suitable for extracting information from
large and complex XML documents, since we would have to know exactly
what the file looks like and where the information needed is located.
From a more general point of view, the structure and semantics of an XML
file is determined by the makeup of the document, its tags and
attributes -- hence, we need a device that is able to recognize and
understand this structure and can point out any errors in it. Moreover,
it has to provide the content of the document through an interface, so
that other applications can access it without difficulty. This device is
known as an XML parser.

### What a parser does

Almost all programs that need to process XML documents use an XML parser
to extract the information stored in the XML document in order to avoid
any of the difficulties that occur when reading and interpreting raw XML
data. The parser usually is a class library (e.g. a set of Java class
files) that reads a given document and checks if it is well-formed
according to the W3C specification. Then, any client software can use
methods of the interface provided by the parser API to access the
information the parser retrieved from the XML file.

All in all, the parser shields the user from dealing with the complex
details of XML like assembling information distributed over several XML
files, checking for well-formedness constraints, and so on.

## Parsing: an Example

To illustrate more clearly what parsing an XML file really means, the
following example was created which contains information about some
cities. It also keeps track of who is on vacation and demonstrates the
parsing process with the currently most common parsing methods.

### Example: *cities.xml*

``` XML
<?xml version="1.0" encoding="UTF-8" ?>
<cities>
<city vacation="Sam">
<cityName>Atlanta</cityName>
<cityCountry>USA</cityCountry>
</city>
<city vacation="David">
<cityName>Sydney</cityName>
<cityCountry>Australia</cityCountry>
</city>
<city vacation="Pune">
<cityName>Athens</cityName>
<cityCountry>Greece</cityCountry>
</city>
</cities>
```

Based on the information stored in this XML document, we can easily
check who is on vacation and where. The parser will read the file using
one of the various techniques presented later in this chapter.

This process is very complicated and prone to errors of all kinds.
Luckily, we will never have to write code for it, because there are
plenty of free, fully-functional parsers on the Web. All we do is
download a parser class library and access the XML document through the
interface provided by the parser software. With more recent builds of
Java, most parsers do not even have to be downloaded. In other words, we
use the functions or methods included in the class library for
extracting the information.

Basically, a parser reads the XML document and tries to recognize the
structure of the file itself while checking for errors. It simply checks
for start/end tags, attributes, namespaces, prefixes, and so on. Then,
the client software can access the information derived from this
structure using methods provided by the parser software (i.e. the
interface).

The best way to learn about the functionality of a parser is to actually
use them; therefore, the next section demonstrates the different methods
of parsing.

## Parser APIs (Application Programming Interface)

### Overview

There are two "traditional" approaches that dominate the market right
now, an event-based push-model as represented by SAX (Simple API for
XML) and a tree-based model using the DOM (document object model)
approach.

However, there is a movement towards newer approaches and techniques
that try to overcome the flaws inherent in these traditional models --
an event-based pull-model and a "cursor model", such as VTD-XML, which
allows us to browse the XML document just like in the tree-based
approach, but simpler and easier to use.

### SAX (Simple API for XML)

#### Description

The push model, typically the exemplified by SAX (www.saxproject.org) is
the "gold standard" of XML parsing, since it is probably the most
complete and accurate method so far. The SAX classes provide an
interface between the input streams from which XML documents are read
and the client software which receives the data made available by the
parser. The parser browses through the whole document and fires events
every time it recognizes an XML construct (e.g. it recognizes a start
tag and fires an event -- the client software is notified and can use
this information... or not).

#### Evaluation

The advantage of such a model is that we don't need to store the whole
XML document in memory, since we are only reading one piece of
information at a time. If you recall that the XML structure is a set of
nodes of various types (like an element node) -- parsing the document
with a SAX parser means going through each node one at a time. This
makes it possible to read even very large XML documents in a
memory-efficient way. However, the fact that the parser only provides
information about the node currently read also implies that the
programmer of the client software is in charge of saving certain
information in a separate data structure (e.g. the parents or children
of the currently processed node). Moreover, the SAX approach is pretty
much read-only, since it is hard to modify the XML structure when we do
not have some sort of global view.

In fact, the parser is in control of what is read when. The user can
only wait until a certain event has occurred and then use the
information stored in the currently processed node.

#### Example: *TGSAXParser.java*

As mentioned before, the best way to fully understand the concept of the
parsing process is to actually use it. In the following code sample, the
information about the name and country of the cities that people are
vacationing in will be displayed. The SAX API that is part of the Xerces
parser package was used for the implementation ((Xerces 2
Homepage):

``` java
// import the basic SAX API classes
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.io.*;

public class TGSAXParser extends DefaultHandler
{
    public boolean onVacation = false;

    // what to do when a start-element event was triggered
    public void startElement(String uri, String name, String qName, Attributes atts)
    {
        // stores the string in the XML file
        String vacationer = atts.getValue("vacation");
        String cityName = atts.getValue("cityName");
        String cityCountry = atts.getValue("cityCountry");

        // if the start tag is "city" set vacationer to true
        if (qName.equals("city") && (vacationer != null))
        {
            onVacation = true;
            System.out.print("\n" + vacationer + " is on vacation in ");
        }
        if (qName.equals("cityName") && onVacation)
            {
            }
        if (qName.equals("cityCountry") && onVacation)
        {
        }
    }

    /**This method is used to stop printing information once the element has
    *been read.  It will also reset the onVacation variable for the next
    *element.
    */
    public void endElement(String uri, String name, String qName)
    {
        //reset flag
        if (qName.equals("city"))
        {
            onVacation = false;
        }
    }

    /**This method is triggered to store and print the values between
    *the XML tags.  It will only print those values if onVacation == true.
    */
    public void characters(char[] ch, int start, int length)
    {
        if (onVacation)
        {
            for (int i = start; i < start + length; i++)
            System.out.print(ch[i]);
        }
    }

    public static void main(String[] args)
    {
        System.out.println("People on vacation in the following cities:");

        try
        {
            // create a SAX parser from the Xerces package
            XMLReader xml = XMLReaderFactory.createXMLReader();
            TGSAXParser handler = new TGSAXParser();
            xml.setContentHandler(handler);
            xml.setErrorHandler(handler);
            FileReader r = new FileReader("cities.xml");
            xml.parse(new InputSource(r));
        }
        catch (SAXException se)
        {
            System.out.println("XML Parsing Error: " + se);
        }
        catch (IOException io)
        {
            System.out.println("File I/O Error: " + io);
        }
    }
}
```

The `DefaultHandler`: As mentioned before, SAX is completely
event-driven. Therefore, we need a handler that "listens" to the input
stream coming from the input file (*cities.xml* in this case).

The SAX API provides interface classes, which we have to extend with our
own code to read our own specific XML document. In order to include our
code in the SAX API, we just have to extend the DefaultHandler interface
with our own class and set the content handler to our custom handler
class (which consists of three methods: startElement, endElement and
characters)

The `startElement()` and `endElement()` methods: These methods are
invoked whenever the SAX parser finds a start or end tag respectively.
The SAX API provides blank stubs for both methods and we have to fill
them with code of our own.

In this case, we want our program to do something whenever the
`vacation` attribute is set, so we set a Boolean variable to true
whenever we find such an element and process the node by printing out
the character sequence in between the start and end tag. The `character`
method is automatically called whenever a `startElement` and
`endElement` event was triggered, but prints out the character string
only if the `onVacation` attribute is set.

### DOM (Document Object Model)

#### Description

The other popular approach is the tree-based model as represented by the
DOM (document object model, see W3C
Recommendation). This method actually
works similarly to a SAX parser, since it reads the XML document from an
input stream by browsing through the file and recognizing XML
structures.

This time, instead of returning the content of the document in a series
of small fragments, the DOM method maps the XML hierarchy to a DOM tree
object that contains everything from the original XML document.
Everything from elements, comments, textual information or processing
instructions is stored in the tree object as nodes, starting with the
document itself as the root node.

Now that all the information we need is stored in memory, we access the
data by using methods provided by the parser software to read or modify
objects within the tree. This facilitates random access to the content
of the XML document and provides the possibility to modify the data it
contains or even create new XML files by transforming a DOM back to an
XML document.

#### Evaluation

However, the major downside of this approach is that it requires much
more memory and is therefore not suitable for situations where large XML
files are used. More importantly, it is somewhat more complex than the
simplistic SAX method even for small and simple problems.

#### Example: *MyDOMParser.java*

In the following code sample, a list of cities with people on vacation
is again created but this time with the tree-based approach:

``` java
// import all necessary DOM API classes
import org.apache.xerces.parsers.*;
import org.apache.xerces.dom.*;
import org.w3c.dom.*;
public class MyDOMParser{
    public static void main(String[] args) {
        System.out.println("People on vacation in the following cities:");
        try {
            // creates a DOM parser object
            DOMParser parser = new DOMParser();
            parser.parse("cities.xml");

            // stores the tree object in a variable
                org.w3c.dom.Document doc  = parser.getDocument();

            // returns a list of all city elements in my city list
            NodeList list = doc.getElementsByTagName("city");

            // now, for every element in the city list, check if the
            // "vacation" attribute is set and if yes, print out the
            // information about the vacationer.
            for(int i = 0, length = list.getLength(); i < length; i++){
                Element city  = (Element)list.item(i);
                Attr vacationer = city.getAttributeNode("vacation");
                if(vacationer!= null){
                    String v = vacationer.getValue();
                    System.out.print(v + " is vacationing in ");

                    // grab information about city name and country
                    // directly from the DOM tree object
                    ParentNode cityname = (ParentNode)
                    doc.getElementsByTagName("cityName").item(0);
                    ParentNode country = (ParentNode)
                    doc.getElementsByTagName("cityCountry").item(0);
                    System.out.println(cityname.getTextContent() + ", " + country.getTextContent());
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
```

_`parser.getDocument()`:_ Once we parsed the XML
document, the tree object is temporarily stored in the parser variable.
In order to work with the DOM object, we have to create a variable
holding it (of type _`org.w3c.dom.Document`_).

Then, we create a _list of nodes holding all elements with
the tag name <city>_. The parser finds
these nodes by browsing through the DOM tree. Then, we just go through
each one of the city-elements and check if the `vacation` attribute is
set and display all the information about the vacationer if so.

Xerces provides a helpful method called
_`getTextContent()`_ that lets us directly access
the text node of an element node, avoiding all difficulties emerging
from unneeded white space and the like.

## Summary

Choosing an API at the beginning of your XML project is a very important
decision. Once you decide which one to use, it is easy to try different
vendors without having much trouble, but switching to a different API
will be a very time-consuming and costly process, since you will have to
redesign your whole program code.

The SAX API is a widely accepted and well-working parser that is easy to
implement and works especially well with streaming content (e.g. an
online XML source). Because it is a read-only API, you would not be able
to modify the underlying XML data source. Since it only reads one node
at a time, it is very memory-efficient and fast. However, this implies
that your application expects the information to be close together and
ordered.

If you want to randomly access the entire document at any point of time,
then the DOM approach might be a better choice for you. The DOM API is
more complex and harder to implement, but gives you full control over
the whole document and lets you modify the data, also. However, it reads
the whole XML document into memory, so the DOM API is not suitable for
projects with very large XML files.

```{=html}
<div style="color:#8b4513">
```
## Exercise

### Recommended optional exercise

*Use the code sample for the SAX and DOM parser from this chapter and
play around with it. You probably want to print out different nodes or
add more constraints. This absolutely optional, but will give you an
idea of the main differences between SAX and DOM.*

### Now for the exercise

-   *Create a SAX parser to parse the file movies.xml. The output simply
    needs to come from your IDE, it does not need to be sent onto a
    webpage.*

*TO HELP YOU* download
this, it provides a
structure of the problem so that you can more easily run the app in
NetBeans 5.0.

If you're interested in using Xerces -- just download the following
file:

`           ``http://www.apache.org/dist/xml/xerces-j/Xerces-J-bin.2.8.0.zip`

If the above link is dead. Go to
<http://www.apache.org/dist/xml/xerces-j/> and download the latest zip
binary file. It should be in the format of \"Xerces-J-bin.#.#.#.zip\"

Then put the content into the \\lib\\ext
subfolder of your NetBeans directory and start up NetBeans IDE. Now, the
Xerces package is successfully installed on your machine.

```{=html}
</div>
```
## Useful Links

1.  <http://www.cafeconleche.org>
2.  <http://www.xml.com>
3.  <http://www.xmlpull.org>
4.  <http://workshop.bea.com/xmlbeans/reference/com/bea/xml/XmlCursor.html>
5.  <http://workshop.bea.com/xmlbeans/reference/com/bea/xml/XmlCursor.html>

{{/Answers}}

fr:Programmation XML/Parsing