0
votes

I have been trying to transform the structure of an XML file using XSLT but i am stuck.

Input:

<products>
<product>
<name>name</name>
<prodoptions>
<prodoption sku="foo" description="description"/>
<prodoption sku="bar" description="otherdescription"/>
</prodoptions>
</product>
</products>

The desired output:

<products>
<product>
<name>name</name>
<sku>foo</sku>
<description>description</description>
</product>
<product>
<name>name</name>
<sku>bar</sku>
<description>otherdescription</description>
</product>
</products>

So far i have been able to use xslt to move the attributes of option into separate child elements and rename a couple of duplicate elements but im stuck creating the second product element for the options. What xlst transform will yield the output?

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="prodoption/@*">
<xsl:element name="{name()}">
<xsl:value-of select="."/>
</xsl:element>
</xsl:template>
<xsl:template match="prodoption/code">
<sku>
<xsl:apply-templates select="@* | node()"/>
</sku>
</xsl:template>
<xsl:template match="prodoption/@code">
<xsl:element name="sku">
<xsl:value-of select="."/>
</xsl:element>
</xsl:template>
<xsl:template match="prodoption/@description">
<xsl:element name="name2">
<xsl:value-of select="."/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>

Thanks

1
Why don't you post your attempt so we can fix it, instead of having to write your code for you from scratch. - michael.hor257k
done sorry about that - max fuller
It would be nice if they matched. I see no prodoption in the given XML. - michael.hor257k

1 Answers

0
votes

I would suggest you change your approach to something like:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/products">
    <xsl:copy>
        <xsl:for-each select="product/options/option">
            <product>
                <xsl:copy-of select="../../name"/>
                <xsl:for-each select="@*">
                    <xsl:element name="{name()}">
                        <xsl:value-of select="."/>
                    </xsl:element>
                </xsl:for-each>
            </product>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Note that this will create a product for each option - and products that do not have any options will not be listed at all.