XML technologies / XML / Perl & XML / Working with trees: XPath, XSLT and more / XPath

(Excerpt from “Perl & XML” by Erik T. Ray & Jason McIntosh)

Imagine a troop of loyal monkeys obeying your every word. You might say: “Please fetch a banana milkshake from the ice-cream shop on Lindenstraße, just across Kudamm.” Not being particularly intelligent—otherwise they would not obey so readily—they return with everything edible they find. You wait for the milkshake and send everything else back. Or send them to evening classes: after several months of learning human language, they could follow instructions precisely, find exactly what you want and bring it much faster.

This is precisely the problem XPath solves. One of XML’s most useful technologies, it selects nodes descriptively without programming loops or if conditions. State which nodes you want and the XPath parser finds them. The confusing pile called an XML document becomes an orderly indexed filing cabinet.

Consider the following XML document:

Example: A preferences file

<preferences>
    <liste>
        <name>DefaultDirectory</name>
        <string>/usr/local/fooby</string>
        <name>RecentDocuments</name>
        <array>
            <string>/Users/bobo/docs/menu.pdf</string>
            <string>/Users/slappy/pagoda.pdf</string>
            <string>/Library/docs/Baby.pdf</string>
        </array>
        <name>BGColor</name>
        <string>sage</string>
    </liste>
</preferences>

A typical preferences file stores a simple list of easily interpreted key/value pairs. To find the value of the key BGColor, find the <name> element containing the string “BGColor”, then the next element of type <string>. Finally, read its text node. With DOM this is fairly easy, as the example below shows.

Example: Reading the preferred background color

sub get_bgcolor {   
   my $doc = shift;
   my @keys = $doc->getElementsByTagName( 'name' );
   foreach my $key ( @keys ) {
      if( $key->getFirstChild->getData eq 'BGColor' ) {
         for (my $elem = $key->getNextSibling; $elem;
            $elem = $elem->getNextSibling) {
         if ($elem->nodeType == ELEMENT_NODE()) {
            return $elem->getFirstChild->getData;
         }
      }
   }
  }
  return;
}

Writing one such function is reasonable; needing hundreds is another matter. This document was simple, so imagine the complexity of larger ones. Could we reduce the work to one source line? It would be easier to read and write, with fewer errors. XPath does exactly that.

XPath describes a node or set of nodes anywhere in a document. Simple yet powerful and standardized by the W3C, it underpins other technologies, especially XSLT, where XPath expressions select transformation rules. Another example is XPointer, an XML language attaching documents to other resources. We will soon see XPath integrated into many Perl modules.

An XPath expression is called a location path and consists of individual steps. Each brings you closer to the desired node or nodes. Start at a known location, such as the document root, and traverse the tree step by step to obtain a node set. Syntax resembles filesystem paths, with steps separated by slash (/).

Express the previous example as a location path:

 /preferences/liste/name[text()='BGColor']/following-sibling::*[1]/text( ) 

Evaluation starts at a fixed location, and each step can lead to one or more new nodes. After each step, the current node becomes the next step’s starting point. If several nodes match, each becomes current in turn, and their result sets are combined. Examine the steps for the path above:

Any step may find several nodes, requiring extra conditions to exclude unwanted ones. For example, among elements of type <name>, exclude those not containing BGColor. Otherwise the result would include every text node in every element immediately following a <name> element.

The following path selects all <name> elements in the example:

 /preferences/liste/name 

Conditions evaluate as Boolean constants. You can test node position within a selected set, child or attribute existence, and numeric comparisons, combining expressions with AND and OR. A bare number abbreviates a position test. Thus the symbol [1] means “ignore everything except the first matching node”.

Boolean expressions inside brackets may be joined with AND, or put in consecutive bracket pairs, implying an invisible AND. Every step also has an implicit condition excluding dead ends. If no node matches, that branch yields nothing and can usually stop, unless searches for earlier selected nodes remain.

An axis can direct a location path like a compass needle. By default, searches descend to children. Axes can instead go up to parents and ancestors or sideways to siblings. Specify the axis as the step’s prefix, separated by double colon (::). The preceding example used the axis following-sibling to find the current node’s next neighbor.

Steps need not select elements: they may select attributes, text, processing instructions or comments. You can even leave the type unspecified by asking for “all node types”. The following list shows the choices:

Symbol

Getroffene Auswahl

node( )

Alle Knoten

text( )

Textknoten

element::foo

Ein Element namens foo

foo

Ein Element namens foo

attribute::foo

Ein Attribut namens foo

@foo

Ein Attribut namens foo

@*

Beliebige Attribute

*

Beliebige Attribute

.

Dieses Element

..

Der Vaterknoten

/

Der Wurzelknoten

/*

Das Wurzelelement

//foo

Ein Element namens foo an einer beliebigen Stelle

Elements are the default because they are requested most often, but other types are useful too. Our example uses text( ) to return the content of the <value> element.

Most steps are relative locators, acting relative to the starting node. Most paths use these, but there are also absolute locators pointing to fixed document locations. The two main ones are id( ), the element with the specified ID, and root( ), the document root, an abstract parent of the root element. At the beginning of paths, / often abbreviates root( ).

Now that our monkeys understand XPath, let us use it in Perl. Matt Sergeant’s module XML::XPath is a solid XPath implementation. This example takes two command-line arguments, a filename and a location path, and prints the textual value of matching nodes.

Example: XPath in action

use XML::XPath;
use XML::XPath::XMLParser;

# Erzeuge ein Objekt, das die Datei liest und die Ausführung von XPath-Queries erlaubt
my $xpath = XML::XPath->new( filename => shift @ARGV );

# Lies den Pfad von der Kommandozeile und erzeuge eine Liste passender Knoten
my $nodeset = $xpath->find( shift @ARGV );

# Gib jeden Knoten in der Liste aus
foreach my $node ( $nodeset->get_nodelist ) {
  print XML::XPath::XMLParser::as_string( $node ) . "\n";
}

The example is simple. Next we need the following test file:

Example: An XML file for testing XPath

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE inventar [
<!ENTITY gift "<hinweis>Vorsicht: Gift!</hinweis>">
<!ENTITY gefaehrdet "<hinweis>Bedrohte Art</hinweis>">
]>
<!-- Inventar der Kräutersammlung von Rivenwood -->
<inventar datum="2001.9.4">
    <kategorie typ="Baum">
        <eintrag id="284">
            <name stil="lateinisch">Carya glabra</name>
            <name stil="deutsch">Ferkelnuß</name>
            <aufbewahrungsort>Ostflügel</aufbewahrungsort>
            &gefaehrdet;
        </eintrag>
        <eintrag id="222">
            <name stil="lateinisch">Toxicodendron vernix</name>
            <name stil="deutsch">Giftsumach</name>
            <aufbewahrungsort>Westliche Ballustrade</aufbewahrungsort>
            &gift;
        </eintrag>
    </kategorie>
    <kategorie typ="Hecke">
        <eintrag id="210">
            <name stil="lateinisch">Cornus racemosa</name>
            <name stil="deutsch">Rispenhartriegel</name>
            <aufbewahrungsort>Südlicher Anbau</aufbewahrungsort>
        </eintrag>
        <eintrag id="104">
            <name stil="lateinisch">Alnus rugosa</name>
            <name stil="deutsch">Runzelerle</name>
            <aufbewahrungsort>Ostflügel</aufbewahrungsort>
            &gefaehrdet;
        </eintrag>
    </kategorie>
</inventar>

The first test uses the path /inventar/kategorie/eintrag/name:

> grabber.pl data.xml "/inventar/kategorie/eintrag/name"
<name stil="lateinisch">Carya glabra</name>
<name stil="deutsch">Ferkelnuß</name>
<name stil="lateinisch">Toxicodendron vernix</name>
<name stil="deutsch">Giftsumach</name>
<name stil="lateinisch">Cornus racemosa</name>
<name stil="deutsch">Rispenhartriegel</name>
<name stil="lateinisch">Alnus rugosa</name>
<name stil="deutsch">Runzelerle</name>

All <name> elements were found and printed. Next try the more specific path /inventar/kategorie/eintrag/name[@stil='lateinisch']:

> grabber.pl data.xml "/inventar/kategorie/eintrag/name[@stil='lateinisch']"
<name stil="lateinisch">Carya glabra</name>
<name stil="lateinisch">Toxicodendron vernix</name>
<name stil="lateinisch">Cornus racemosa</name>
<name stil="lateinisch">Alnus rugosa</name>

Now use the path //eintrag[@id='222']/hinweis to start from the ID attribute. If declared as ID in a DTD, we could simply write id('222')/hinweis. We did not do so, but the first approach works.

> grabber.pl data.xml "//eintrag[@id='222']/hinweis"
<hinweis>Vorsicht: Gift!</hinweis>

Find the “hinweis” tags distracting? No problem:

> grabber.pl data.xml "//eintrag[@id='222']/hinweis/text( )"
Vorsicht: Gift!

When was the last inventory?

> grabber.pl data.xml "/inventar/@datum"
  datum="2001.9.4"

XPath can eventually become confusing too. A bewildered monkey might follow this path:

> grabber.pl data.xml "//*[@id='104']/parent::*/preceding-sibling::*/child::*[2]/
name[not(@stil='lateinisch')]/node( )"
Giftsumach

The monkey first finds the element with the value '104' in the attribute id. It then climbs one level, jumps to the previous element, descends to the second child, finds a <name> whose attribute stil has the value lateinisch, then selects its child containing the text node “Giftsumach”.

We have used XPath to find and collect nodes. Next consider a more sophisticated implementation. XML::Twig, Michel Rodriguez’s clever module, fits Perl particularly well. It maps expressions to subroutines, allowing custom functions for particular node types.

The next example demonstrates this. When initializing the XML::Twig object, pass a hash of handlers whose keys are XPath expressions. The parser builds a tree and calls the relevant handler whenever a node matches.

Notice the at sign (@) treated specially because of its Perl meaning. In XPath, @foo denotes the attribute foo rather than the Perl array foo. Remember this distinction throughout these examples and your own Perl XPath programs. Always escape the at sign with a backslash to prevent array interpretation.

If your code uses more Perl arrays than XPath attribute references, consider the full axis name “attribute”: attribute::foo. Double colon also differs in Perl and XPath, but XPath has few hard-coded, necessarily lowercase axis names, so confusion should be limited.

Example: Working with Twig handlers

use XML::Twig;

# Buffer zum Aufnehmen von Text
my $cat_buf = '';
my $eintrag_buf = '';

# Initialisierung des Parsers mit Handlern zur Verarbeitung von Knoten
my $twig = new XML::Twig( TwigHandlers => {                              
                              "/inventar/kategorie" => \&kategorie,
                              "name[\@stil='lateinisch']" => \&name_lateinisch,
                              "name[\@stil='deutsch']" => \&name_deutsch,
                              "kategorie/eintrag" => \&eintrag,
                                 });

# Parsen der Datei, mit Aufruf der Handler
$twig->parsefile( shift @ARGV );    

# Ein Element "kategorie" wurde gefunden
sub kategorie {
    my( $tree, $elem ) = @_;
    print "Kategorie: ", $elem->att( 'typ' ), "\n\n", $cat_buf;
    $cat_buf = '';
}

# Ein Element "eintrag" wurde gefunden
sub eintrag {
    my( $tree, $elem ) = @_;
    $cat_buf .= "Eintrag: " . $elem->att( 'id' ) . "\n" . $eintrag_buf . "\n";
    $eintrag_buf = '';
}

# Behandlung eines lateinischen Namens
sub name_lateinisch {
    my( $tree, $elem ) = @_;
    $eintrag_buf .= "Lateinischer Name: " . $elem->text . "\n";
}

# Behandlung eines deutschen Namens
sub name_deutsch {
    my( $tree, $elem ) = @_;
    $eintrag_buf .= "Deutscher Name: " . $elem->text . "\n";
}

The program reads a file like Example 8-7 and prints a summary. Handlers run only once an element is fully built, so their order may seem unnatural: children precede parents. We must therefore buffer output for later.

The result is:

Kategorie: Baum

Eintrag: 284
Lateinischer Name: Carya glabra
Deutscher Name: Ferkelnuß

Eintrag: 222
Lateinischer Name: Toxicodendron vernix
Deutscher Name: Giftsumach
Kategorie: Hecke

Eintrag: 210
Lateinischer Name: Cornus racemosa
Deutscher Name: Rispenhartriegel

Eintrag: 104
Lateinischer Name: Alnus rugosa
Deutscher Name: Runzelerle

XPath drastically simplifies finding nodes and describing what to process. Navigation code shrinks to a readable minimum, which is extremely satisfying. Being a standard, XPath will likely appear in many other modules.

  

  

 

 

 

back to top