Previous | Next | Indexes
Zvon > Tutorials > XSLT 2.0 Tutorial > Recursions (5/6) >

Recursive change of the value of attributes

In this example we want to change a value of attribute if it already exists and to preserve all other attributes intact. The xsl:copy-of in this example copies all attributes with the exception of the one we want to change.

xsl:apply-templates without the select attribute applies templates to all children nodes (text, elements, ...) - the recursive step. The other xsl:apply-template processes existing "r" attributes. The xsl:attribute multiplies the value of this attribute by 5, or more precisely creates a new attribute with the same name and with value based on the original value.

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="@*[name() != 'r']"/>
                        <xsl:apply-templates  select="@r"/>
                        <xsl:apply-templates/>
                  </xsl:copy>
            </xsl:template>

            <xsl:template  match="@r">
                  <xsl:attribute  name="r"
                              select=". * 5"/>
            </xsl:template>

      </xsl:stylesheet>
XML

      <aaa  a="aaa">
            <bbb  r="11"/>
            <ccc  u="1"
                        v="2">
                  <ddd  r="7"
                              s="12"/>
                  <eee  r="3"
                              s="27"/>
            </ccc>
      </aaa>
Output

      <aaa  a="aaa">
            <bbb  r="55"/>
            <ccc  u="1"
                        v="2">
                  <ddd  s="12"
                              r="35"/>
                  <eee  s="27"
                              r="15"/>
            </ccc>
      </aaa>


Previous chapter: Keys
Next chapter: Date and Time
Previous page: Recursive addition of attributes
Next page: Recursive processing of text nodes