Tuesday, March 27, 2012

Copy name and value with XSLT

I run across a situation where I had to map a huge list of sibling nodes. I was required to send tuples of name (in upper case) and value. If they were few, I would use a Table Looping like always, but this time it was a lot of fields and I was feeling lazy. Here is the solution.

<xsl:variable name="smallcase" select="'abcdefghijklmnopqrstuvwxyz'" />
<xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" />


            <xsl:for-each select="//Data/item/*">
                  <xsl:element name="ns0:GenericDataContainerEntry">
                        <xsl:element name="ns0:GenericDataContainerEntryIndex">
                              <xsl:attribute name="value">
                                    <xsl:value-of select="./text()" />
                              xsl:attribute>
                              <xsl:attribute name="name">
                                    <xsl:value-of select="translate(name(.),$smallcase,$uppercase)" />
                              xsl:attribute>
                        xsl:element>
                  xsl:element>
            xsl:for-each>
      xsl:for-each>
xsl:element>


Do to all nodes

<xsl:for-each select="//Data/item/*">

Copy value

<xsl:value-of select="./text()" />

Copy name

<xsl:value-of select="name(.)" />


Copy name in upper case in XSLT 1.0 (found it here)

<xsl:variable name="smallcase" select="'abcdefghijklmnopqrstuvwxyz'" />
<xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" />
<xsl:value-of select="translate(name(.),$smallcase,$uppercase)" />

No comments: