Inside Xslt

Using the preceding Axis

The preceding axis contains all nodes that are before the context node in document order, excluding any ancestors of the context node, and also excluding attribute nodes and namespace nodes.

For example, say that I want to set the content of the <DISTANCE> element to the text This planet is farther from the Sun than Mercury. if the current planet is indeed farther from the Sun than Mercury. One way to do that is to see whether Mercury comes before the current planet in document order, using the preceding axis:

Listing 7.13 Using the preceding 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="DISTANCE[preceding::*/NAME='Mercury']"> <DISTANCE>This planet is farther from the Sun than Mercury.</DISTANCE> </xsl:template> <xsl:template match="@*node()"> <xsl:copy> <xsl:apply-templates select="@*node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet>

If the current planet does come after Mercury, I can insert the message in its <DISTANCE> element. 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 UNITS="million miles">43.4</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>This planet is farther from the Sun than Mercury.</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>This planet is farther from the Sun than Mercury.</DISTANCE> <!--At perihelion--> </PLANET> </PLANETS>

Категории