In this example attributes are added to all elements. xsl:copy copies the matching element node from the source document (without attribute and descendant nodes) and xsl:copy-of adds to these elements already existing attributes. The values of new attributes are set to the value of position() function and to the number of elements on "preceding-sibling::" axis. The values of these attributes always differ by one. If you understand the process of templates matching you know that it is not a coincidence.
|
XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"> <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/> <xsl:template match="*"> <xsl:copy> <xsl:copy-of select="@*"/> <xsl:attribute name="a" select="position()"/> <xsl:attribute name="z" select="count(preceding-sibling::*)"/> <xsl:apply-templates select="*"/> </xsl:copy> </xsl:template> </xsl:stylesheet> |
|
|
XML
<aaa> <bbb r="11"/> <ccc> <ddd r="7" s="12"/> <eee r="3" s="27"/> </ccc> </aaa> |
Output
<aaa a="1" z="0"> <bbb r="11" a="1" z="0"/> <ccc a="2" z="1"> <ddd r="7" s="12" a="1" z="0"/> <eee r="3" s="27" a="2" z="1"/> </ccc> </aaa> |
| Previous chapter: | Keys |
| Next chapter: | Date and Time |
| Previous page: | Recursive renaming of elements |
| Next page: | Recursive change of the value of attributes |