tags:

views:

71

answers:

3

Hi,

I need to create an XSLT which tranforms an attribute in the source xml to a new element in the target xml with the element name assigned the "Name" value of the attribute in the source xml.

Eg:

Source:

<ProductType>Fridge</ProductType>
    <Features>
      <Feature Name="ValveID">somename</Feature>
      <Feature Name="KeyIdentifier">someID</Feature>

Result:

<Fridge>
    <Feature>somename</Feature>
    <Feature>someID</Feature>

Expected Result:

  <Fridge>
        <ValueID>somename</ValueID>
        <KeyIdentifier>someID</KeyIdentifier>

My XSLT looks like this for now:

1 <Fridge>
2       <xsl:for-each select="$var6_ProductData/Features/Feature">
3            <xsl:variable name="var8_Feature" select="."/>
4            <xsl:element name="{name()}">
5                 <xsl:value-of select="string($var8_Feature)"/>
6            </xsl:element>
7       </xsl:for-each>
8 </Fridge>

I need to change line 4 but not sure how. Any ideas??


D

+2  A: 

I would try

<xsl:element name="{@Name}">

as name() gives you the name of the XML element "Feature" (selected by the xsl:for-each), not the content of the current node's Name= attribute.

ndim
Yes this works too.
Dipesh
A: 

Figured it out:

1 <Fridge>
2       <xsl:for-each select="$var6_ProductData/Features/Feature">
3            <xsl:variable name="var8_Feature" select="."/>
3            <xsl:variable name="var9_Feature" select="@Name"/>
4            <xsl:element name="{$var9_Feature}">
5                 <xsl:value-of select="string($var8_Feature)"/>
6            </xsl:element>
7       </xsl:for-each>
8 </Fridge>
Dipesh
Dipesh, I would go with Tomalak's implementation as it is generic and provides more flexibility for enhancements
Rashmi Pandit
+4  A: 

Generic solution (and more idiomatic, too):

<xsl:template match="ProductType">
  <xsl:element name="{text()}">
    <xsl:apply-templates select="Features/Feature" />
  </xsl:elemment>
</xsl:template>

<xsl:template match="Features/Feature">
  <xsl:element name="{@Name}">
    <xsl:value-of select="text()" />
  </xsl:elemment>
</xsl:template>

<ProductType> elements are transformed into a new element with a dynamic name, same goes for <Feature> elements.

Tomalak