Using the ancestor-or-self Axis

Using the ancestor -or-self Axis

The ancestor-or-self axis contains all the ancestors of the context node, as well as the context node itself. That means, among other things, that this axis always contains the root node.

In the following example, Ive added an AUTHOR attributes set to Steve throughout this document:

Listing 7.4 planets.xml with AUTHOR Attributes
 <?xml version="1.0"?>  <?xml-stylesheet type="text/xml" href="planets.xsl"?>  <PLANETS AUTHOR="Steve" >      <PLANET AUTHOR="Steve">          <NAME>Mercury</NAME>          <MASS AUTHOR="Steve" UNITS="(Earth = 1)">.0553</MASS>          <DAY UNITS="days">58.65</DAY>          <RADIUS UNITS="miles">1516</RADIUS>          <DENSITY UNITS="(Earth = 1)">.983</DENSITY>          <DISTANCE UNITS="million miles">43.4</DISTANCE><!--At perihelion-->      </PLANET>      <PLANET AUTHOR="Steve">          <NAME>Venus</NAME>          <MASS UNITS="(Earth = 1)">.815</MASS>          <DAY UNITS="days">116.75</DAY>          <RADIUS UNITS="miles">3716</RADIUS>          <DENSITY UNITS="(Earth = 1)">.943</DENSITY>          <DISTANCE UNITS="million miles">66.8</DISTANCE><!--At perihelion-->      </PLANET>      <PLANET>          <NAME>Earth</NAME>          <MASS UNITS="(Earth = 1)">1</MASS>          <DAY UNITS="days">1</DAY>          <RADIUS UNITS="miles">2107</RADIUS>          <DENSITY UNITS="(Earth = 1)">1</DENSITY>          <DISTANCE UNITS="million miles">128.4</DISTANCE><!--At perihelion-->      </PLANET>  </PLANETS> 

Now say that I want to list all ancestors of <MASS> elements, by name, that have an AUTHOR attributeas well as the current <MASS> element, if it has an AUTHOR attribute. I can do that with the ancestor-or-self axis and the local-name function:

Listing 7.5 Using the ancestor-of-self Axis
 <?xml version="1.0"?>  <xsl:stylesheet version="1.0"  xmlns:xsl="">  <xsl:output method="xml"/>  <xsl:template match="MASS">      <xsl:for-each select="ancestor-or-self::*[@AUTHOR]">          <xsl:value-of select="local-name(.)"/>          <xsl:text> </xsl:text>      </xsl:for-each>  </xsl:template>  <xsl:template match="PLANET">      <xsl:apply-templates select="MASS"/>  </xsl:template>  </xsl:stylesheet> 

Heres the result, showing the matching ancestors of all three <MASS> elements, including the <MASS> element itself if it has an AUTHOR attribute:

 <?xml version="1.0" encoding="UTF-8"?>      PLANETS PLANET MASS      PLANETS PLANET      PLANETS 

Inside XSLT
Inside Xslt
ISBN: B0031W8M4K
Year: 2005
Pages: 196

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: