You can take advantage of a number of abbreviations in XPath
syntax. Here are the rules:
Expression
Abbreviation
self::node()
.
parent::node()
..
child::childname
childname
attribute::childname
@childname
/descendant-or-self::node()/
//
You can also abbreviate predicate expressions such as [position()
= 3] as [3], [position() = last()] as [last()], and so on. Using the
abbreviated syntax makes XPath expressions a lot easier to use. Here
are some examples of location paths using abbreviated syntax-note how
well these fit the syntax we saw with the match attribute earlier in
the chapter:
Path
Description
PLANET
‑Returns the <PLANET> element children of the context
node.
*
‑Returns all element children of the context node.
text()
‑Returns all text node children of the context node.
@UNITS
‑Returns the UNITS attribute of the context node.
@*
Returns all the attributes of the context node.
PLANET[3]
‑Returns the third <PLANET> child of the _context
node.
PLANET[first()]
‑Returns the first <PLANET> child of the context node
*/PLANET
‑Returns all <PLANET> grandchildren of the context
node.
/PLANETS/PLANET[3]/NAME[2]
‑Returns the second <NAME> element of the third
<PLANET> element of the <PLANETS> _element.
//PLANET
‑Returns all the <PLANET> descendants of the document
root.
PLANETS//PLANET
‑Returns the <PLANET> element descendants of the
<PLANETS> element children of the context node.
//PLANET/NAME
‑Returns all the <NAME> elements that have an
<PLANET> parent.
.
Returns the context node itself.
.//PLANET
‑Returns the <PLANET> element descendants of the context
node.
..
Returns the parent of the context node.
../@UNITS
‑Returns the UNITS attribute of the parent of the context
node.
PLANET[NAME]
‑Returns the <PLANET> children of the context node that
have <NAME> children.
PLANET[NAME="Venus"]
‑Returns the <PLANET> children of the context node that
have <NAME> children with text equal to Venus.
PLANET[@UNITS =
"days"]
‑Returns all <PLANET> children of the context node that
have a UNITS attribute with value days.
PLANET[6][@UNITS =
"days"]
‑Returns the sixth <PLANET> child of the context node,
only if that child has a UNITS attribute with value days. Can also be
written as PLANET[@UNITS = "days"][6].
PLANET[@COLOR and
@UNITS]
‑Returns all the <PLANET> children of the context node
that have both a COLOR attribute and a UNITS attribute.
Here's an example in which I put the abbreviated syntax to work,
moving up and down inside a <PLANET> element:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="PLANETS">
<HTML>
<xsl:apply-templates select="PLANET"/>
</HTML>
</xsl:template>
<xsl:template match="PLANET">
<xsl:apply-templates
select="MASS"/>
</xsl:template>
<xsl:template match="MASS">
<xsl:value-of
select="../NAME"/>
<xsl:value-of
select="../DAY"/>
<xsl:value-of
select="."/>
</xsl:template>
</xsl:stylesheet>