Forum Moderators: open
Original:
<?xml version="1.0" encoding="utf-8"?>
<dataset xmlns:xs="http://www.w3.org/2001/XMLSchema-instance">
<metadata>
<item name="Product Id"/>
<item name="Product Type"/>
<item name="Product Name"/>
</metadata>
<data>
<row>
<value>1</value>
<value>Car</value>
<value>Honda</value>
</row>
<row>
<value>2</value>
<value>Motorcycle</value>
<value>Harley</value>
</row>
</data>
</dataset>
Desired Output
<?xml version="1.0" encoding="utf-8"?>
<dataset xmlns:xs="http://www.w3.org/2001/XMLSchema-instance">
<row>
<Product Id>1</Product Id>
<Product Type>Car</Product Type>
<Product Name>Honda</Product Name>
</row>
<row>
<Product Id>2</Product Id>
<Product Type>Motorcycle</Product Type>
<Product Name>Harley</Product Name>
</row>
</dataset>
I need to handle the metadata/items dynamically. Meaning that there could be any number of metadata/items (it's not always 3 as shown in the example).
I've been trying to figure this out, but no luck yet. I've resorted to using programming code (.Net) to parse and rewrite the xml, but if it's possible to do this using XSL, I'd like to handle it that way.
Thanks in advance for your help.
<?xml version="1.0"?>
<!-- [webmasterworld.com...] -->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="no" encoding="utf-8"/>
<xsl:template match="/">
<xsl:element name="row">
<xsl:element name="dataset">
<xsl:apply-templates/>
</xsl:element>
</xsl:element>
</xsl:template><xsl:template match="row">
<xsl:for-each select="value">
<xsl:variable name="try"><xsl:value-of select="position()"/></xsl:variable>
<xsl:variable name="myvar">
<xsl:value-of select="translate(../../../metadata/item[position()=$try]/@name, ' ', '_')"/>
</xsl:variable>
<xsl:element name="{$myvar}">
<xsl:value-of select="."/>
</xsl:element>
</xsl:for-each>
</xsl:template></xsl:stylesheet>