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

Recursive renaming of elements

In the example the elements with names beginning with "n-" are sent to different namespace. The function substring() extract a substring from the string provided as the first argument. The substring starts at the position specified by the second argument, the third argument specifies number of characters of the substring. If this argument is not provided the substring() returns substring from the position given by the second argument to the end of the original string.

For elements which names do not start with "n-" common template "*" is used. In both templates note the position of xsl:apply-templates element.

xsl:copy copies the matched element to the output (without its descendants and attribute nodes - compare with copy-of which copies everything).

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:apply-templates/>
                  </xsl:copy>
            </xsl:template>

            <xsl:template  match="*[substring(name(),1,2)='n-']">
                  <xsl:element  name="n:{substring(name(),3)}"
                              namespace="nnn-namespace">
                        <xsl:apply-templates/>
                  </xsl:element>
            </xsl:template>

      </xsl:stylesheet>
XML

      <aaa>
            <n-bbb>
                  <ccc/>
                  <n-ddd/>
            </n-bbb>
            <eee>
                  <fff>
                        <n-ggg/>
                  </fff>
                  <hhh/>
            </eee>
      </aaa>
Output

      <aaa>
            <n:bbb
                        xmlns:n="nnn-namespace">
                  <ccc/>
                  <n:ddd/>
            </n:bbb>
            <eee>
                  <fff>
                        <n:ggg
                                    xmlns:n="nnn-namespace"/>
                  </fff>
                  <hhh/>
            </eee>
      </aaa>


Previous chapter: Keys
Next chapter: Date and Time
Previous page: Recursive xsl:apply-templates
Next page: Recursive addition of attributes