i-Lab Guide To: XPath

What Is It ?

XPath is the XML node selection syntax used in XSLT (e.g. in the select attribute of xsl:templates). It allows selection of any of the XML node types :-

  • Elements
  • Attributes
  • Processing Instructions
  • Comments

...from absolute or relative paths through the parsed XML document tree. Relative paths are interpreted relative to the current "context".

   
Relative Paths  
"child"
Selects all child nodes in at the level of the current context
"@attribute" Selects the named attribute from the current context
"child/@attribute" Selects the named attribute from the child nodes
"." Selects the current context node
".." Selects the parent node

Absolute Paths

 
"/root/child/leaf"
Selects all leaf elements descended from child and root elements
"/"
Selects all nodes at the root level
Predicates  
"line[3]" 3rd line element
"line[3|7]" 3rd or 7th line element
"line[position() = 3]" 3rd line element
"line[last()]" Last line element
"line[position() mod 2]" Every other line element
"line[@type]" Elements with a type attribute defined
"line[@type='xxx']" Elements with a type attribute whose value equals xxx
Operators  
+, -, * Standard maths operators
div Float division
mod Returns the modulus (remainder)
&lt; Less than ('<' can't be used due to confusion with tag syntax)
&gt; Greater than ('>' can't be used due to confusion with tag syntax)
Axes  
"child::xxx" Abbreviated form "xxx"
"parent::xxx" Abbreviated form ".."
"self::xxx" Abbreviated form "."
"attribute::xxx" Abbreviated form "@xxx"
"ancestor::xxx"  
"ancestor-or-self::xxx"  
"descendant::xxx"  
"descendant-or-self::xxx"  
"preceding-sibling::xxx"  
"following-sibling::xxx"  
"preceding::xxx"  
"following::xxx"  
"namespace::xxx"  
Functions  
position()  
last() Returns the position of the last node in the node-set
   

© 2003 i-Lab Limited