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:
<?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:
<?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="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