XML technologies / XML / Python & XML / Querying XML with XPath / Location paths

(Excerpt from “Python & XML” by Christopher A. Jones & Fred L. Drake, Jr.)

The most common XPath expressions are location paths. A location path resembles a disk path, but is much more powerful. File-system paths contain only directory and file names; an XPath location path can specify much more. Each step can select document nodes using complex tests and may return several nodes. Tests, or predicates, may succeed or fail based on element name, attribute existence or value, or text content.

Full location-path syntax is complex, so the specification defines shortcuts for the commonest tests, called abbreviated location paths. This section uses abbreviated syntax throughout; consult the specification for full syntax and selection capabilities.

Location paths appear in XSLT elements, but can also be used programmatically through an XPath API to return node sets at runtime. This section covers the latter; the former appears in Transforming XML with XSLT.

A sample document

Start with a record-oriented sample. Records are similar, with differing field values, typical of documents queried with XPath. We apply expressions to XML describing spacecraft from popular science-fiction television series.

 

Example: ships.xml

<?xml version="1.0" encoding="UTF-8"?>
<shiptypes name="United Federation of Planets">
  <ship name="USS Enterprise">
    <class>Sovereign</class>
    <captain>Jean-Luc Picard</captain>
    <registry-code>NCC-1701-E</registry-code>
  </ship>
  <ship name="USS Voyager">
    <class>Intrepid</class>
    <captain>Kathryn Janeway</captain>
    <registry-code>NCC-74656</registry-code>
  </ship>
  <ship name="USS Enterprise">
    <class>Galaxy</class>
    <captain>Jean-Luc Picard</captain>
    <registry-code>NCC-1701-D</registry-code>
  </ship>
  <ship name="USS Enterprise">
    <class>Constitution</class>
    <captain>James T. Kirk</captain>
    <registry-code>NCC-1701</registry-code>
  </ship>
  <ship name="USS Sao Paulo">
    <class>Defiant</class>
    <captain>Benjamin L. Sisko</captain>
    <registry-code>NCC-75633</registry-code>
  </ship>
</shiptypes>

A path-hosting script

The file ships.xml provides good XML data for testing paths. Write a small program to apply expressions and examine returned nodes. The next example creates a script, xp.py, calling the function xml.xpath.Evaluate included in 4Suite and recent PyXML versions.

Example: xp.py

"""
xp.py (benötigt ein XML-Dokument auf STDIN)
"""
import sys

from xml.dom.ext.reader import PyExpat
from xml.xpath import Evaluate

path0 = "ship/captain" # alle captain-Elemente

reader = PyExpat.Reader( )
dom = reader.fromStream(sys.stdin)

captain_elements = Evaluate(path0, dom.documentElement)
for element in captain_elements:
  print "Element: ", element

Run it using the file created in example ships.xml, namely ships.xml:

 $ python xp.py < ships.xml 

In the example xp.py, the path ship/captain extracts all captain elements from the document ships.xml. The result is a node list containing:

<captain>Jean-Luc Picard</captain>
<captain>Kathryn Janeway</captain>
<captain>Jean-Luc Picard</captain>
<captain>James T. Kirk</captain>
<captain>Benjamin L. Sisko</captain>

This is not a complete, standalone document, just a node list. The remaining program processes those nodes:

captain_elements = Evaluate(path0, dom.documentElement)
for element in captain_elements:
  print "Element: ", element

The path ship/captain is relative: it does not specify an exact root-to-element location as /shiptypes/ship/captain does. The expression ship/captain returns captain elements that are children of a ship element, relative to the document node passed to Evaluate.

Accessing character data

Often you want text beneath an element, for example the captain’s name rather than its element node. Add XPath’s function text to the expression:

path1 = "ship/captain/text( )"

This selects all text nodes beneath the captain element. Replace the original output lines with:

captainnodes = Evaluate(path1, dom.documentElement)
for captainnode in captainnodes:
  print "Sternenflotten-Captain: ", captainnode.nodeValue

The result is:

$ python xp.py < ships.xml
Sternenflotten-Captain: Jean-Luc Picard
Sternenflotten-Captain: Kathryn Janeway
Sternenflotten-Captain: Jean-Luc Picard
Sternenflotten-Captain: James T. Kirk
Sternenflotten-Captain: Benjamin L. Sisko

Specifying an index

Data processing often depends on positions in columns, rows or arrays. XML is no exception. XPath offers indexing syntax resembling array subscripts, but XPath starts at one while Python sequences start at zero. Put square brackets after the element name to access an indexed element:

 path2 = "ship[2]/captain/text( )" 

Here ship[2] indicates that the second ship element of each parent of ship elements should have the text node beneath its captain element selected. Change the code to display it:

capnode = Evaluate(path2, dom.documentElement)
print "Captain von ship[2] ist: ", capnode[0].nodeValue

With path2, output becomes:

$ python xp.py < ships.xml
Captain von ship[2] ist: Kathryn Janeway

Do not be misled by the visual similarity between ship[2] and Python indexing: they differ greatly. The notation abbreviates ship[position( )=2], meaning the second ship child of any other element matches. Consider this XML:

<fleet name="Atlantic">
  <ship id="id1"/>
  <lifeboat id="id2"/>
</fleet>
<fleet name="Pacific">
  <lifeboat id="id3"/>
  <ship id="id4"/>
  <ship id="id5"/>
</fleet>

The XPath expression ship[2] matches only the ship element whose id attribute is id5. This is not a trick, but a good reason to keep the XPath specification handy.

Testing child nodes

You may want to query text beneath an element name. For chapters with headings and paragraphs, you might seek text under a particular heading. XPath conveniently tests text-node data beneath a specified element. For an element <ship> containing an element <class> with the word Intrepid, use this path:

 path3 = 'ship[class="Intrepid"]' 

It finds ship elements with a class child whose character data contains Intrepid. Further code can examine the resulting list:

shipnodes = Evaluate(path3, dom.documentElement)
for shipnode in shipnodes:   
   shipname = shipnode.getAttribute("name")
   captain = Evaluate("captain/text( )", shipnode)
   print "------------ Schiff der Intrepid-Klasse ------------"
   print "Name: ", shipname
   print "Captain: ", captain[0].nodeValue

Here we find ship nodes with a class child identifying them as Intrepid class ships. Process them again for ship and captain names, producing:

$ python xp.py < ships.xml
------------ Schiff der Intrepid-Klasse ------------
Name: USS Voyager
Captain: Kathryn Janeway

Instead of only checking with path3 whether a child contains required information, extend the path to seek something specific beneath the matching element:

 path4 = 'ship[class="Constitution"]/@name' 

This goes further: first select a ship element only when its class child contains the character data Constitution. Then extend the path to select the name attribute of the ship element having that child text. The symbol @ identifies an attribute rather than a child element. Adapt the code for the new node list:

ship = Evaluate(path4, dom.documentElement)
print "Name des Schiffes der Constitution-Klasse: ", ship[0].nodeValue

Output follows:

$ python xp.py < ships.xml
Name des Schiffes der Constitution-Klasse: USS Enterprise

Testing attributes

Attributes and their contents require a slightly different approach from elements and text nodes. XPath uses the symbol @ for attributes. Square brackets surround nodes being tested for text. Use a path like this to test attribute contents:

 path5 = 'ship[@name="USS Enterprise"]' 

It selects all ship elements whose name attribute contains Enterprise. Your ships.xml file has three ships named Enterprise, with slightly different registration codes. Search the list for more information:

ships = Evaluate(path5, dom.documentElement)   
for shipnode in ships:
   registry = Evaluate("registry-code/text( )", shipnode)
   captain = Evaluate("captain/text( )", shipnode)
   print "Enterprise gefunden mit Registrierung:", registry[0].nodeValue
   print "Captain: ", captain[0].nodeValue

The following relative expressions select the texts captain and registry-code of the current element on each iteration. With the preceding code, output is:

$ python xp.py < ships.xml
Enterprise gefunden mit Registrierung: NCC-1701-E
Captain: Jean-Luc Picard
Enterprise gefunden mit Registrierung: NCC-1701-D
Captain: Jean-Luc Picard
Enterprise gefunden mit Registrierung: NCC-1701
Captain: James T. Kirk

Selecting elements

As with any ordered data, you often want a particular kind of information from the whole document: employee names, for example. With deeply nested data, you may need every occurrence regardless of location. XPath’s path expression // selects all matching elements beneath the root:

 path6 = "/shiptypes//captain" 

This selects every captain element below the root wherever it appears. Accessing character data requires the earlier techniques or traversing the node structure:

captains = Evaluate(path6, dom.documentElement)
for captain in captains:
  print "Captain: ", captain.firstChild.nodeValue

Running path6 produces:

$ python xp.py < ships.xml
Captain: Jean-Luc Picard
Captain: Kathryn Janeway
Captain: Jean-Luc Picard
Captain: James T. Kirk
Captain: Benjamin L. Sisko

Additional operators

Familiarity with Windows or Unix paths probably means you know the operators . and ... The operator . means the current directory, or current XPath element, while .. identifies its parent. With ships.xml from the example ships.xml, find a ship by name, then access its parent to determine its organization.

 path7 = "ship[@name='USS Voyager']/../@name" 

This finds a ship element whose name attribute equals “USS Voyager”, then selects its parent’s name attribute. In ships.xml it is the name attribute of the element shiptypes. Modify the code in xp.py to display the result:

org = Evaluate(path7, dom.documentElement)
print "USS Voyager gehört", org[0].nodeValue

Now xp.py produces output assigning Voyager to the “Federation of Planets”:

$ python xp.py < ships.xml
USS Voyager gehört United Federation of Planets

  

 

 

 

back to top