Using the preceding-sibling Axis

Using the preceding -sibling Axis

The preceding-sibling axis contains all the preceding siblings of the context node. Note that if the context node is an attribute node or a namespace node, the preceding-sibling axis is empty.

For example, what if you wanted to write a template that would match only <DISTANCE> elements in Mercurys <PLANET> element? One way to do that is to check whether any siblings preceding the <DISTANCE> element are < NAME > elements whose string value is Mercury. If you use the preceding-sibling axis, the search is restricted to the current <PLANET> element, which means theres no chance of matching Mercury unless youre in the correct <PLANET> element:

Listing 7.14 Using the preceding-sibling Axis
 <?xml version="1.0"?>  <xsl:stylesheet version="1.0"  xmlns:xsl="">  <xsl:output method="xml"/>    <xsl:template match="DISTANCE[preceding-sibling::*='Mercury']">      <DISTANCE>This is the planet Mercury, closest to the Sun.</DISTANCE>    </xsl:template>    <xsl:template match="@*node()">      <xsl:copy>        <xsl:apply-templates select="@*node()"/>      </xsl:copy>    </xsl:template>  </xsl:stylesheet> 

And heres the result:

 <?xml version="1.0" encoding="utf-8"?>  <?xml-stylesheet type="text/xml" href="planets.xsl"?>  <PLANETS>      <PLANET>          <NAME>Mercury</NAME>          <MASS UNITS="(Earth = 1)">.0553</MASS>          <DAY UNITS="days">58.65</DAY>          <RADIUS UNITS="miles">1516</RADIUS>          <DENSITY UNITS="(Earth = 1)">.983</DENSITY>          <DISTANCE>This is the planet Mercury, closest to the Sun.</DISTANCE>          <!--At perihelion-->      </PLANET>      <PLANET>          <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> 

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

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