Using the descendant Axis

Using the descendant Axis

The descendant axis contains all the descendants of the context node. Note that this does not include any attributes or namespace nodes, because they are not considered child nodes.

The following example puts this axis to work; in this case, I want to add an annotation to Mercurys <PLANET> element: <INFO>Sorry, Mercury has blown up and is no longer available.</INFO> . To find Mercury, all I have to do is to check whether any descendant of a <PLANET> element has the string value Mercury, which I do in an XPath expression inside a match predicate:

Listing 7.6 Using the descendant Axis
 <?xml version="1.0"?>  <xsl:stylesheet version="1.0"  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">  <xsl:output method="xml"/>    <xsl:template match="PLANET[descendant::*='Mercury']">      <xsl:copy>        <xsl:apply-templates select="@*node()"/>        <INFO>Sorry, Mercury has blown up and is no longer available.</INFO>      </xsl:copy>    </xsl:template>    <xsl:template match="@*node()">      <xsl:copy>        <xsl:apply-templates select="@*node()"/>      </xsl:copy>    </xsl:template>  </xsl:stylesheet> 

Heres the result document, complete with the new <INFO> element, for Mercury only:

 <?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 UNITS="million miles">43.4</DISTANCE><!--At perihelion-->         <INFO>Sorry, Mercury has blown up and is no longer available.</INFO>      </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>          .          .          .  </PLANETS> 


Inside XSLT
Inside Xslt
ISBN: B0031W8M4K
EAN: N/A
Year: 2005
Pages: 196

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net