xsl to group child elements into parent tag

I need to transform item tags into their respective parent node with xslt.

I have this input.

<root>
<field>111</field>
<list1>
    <item>
        <field1>aa</field1>
        <field2>valuea</field2>
    </item>
    <item>
        <field1>bb</field1>
        <field2>valueb</field2>
    </item>
</list1>
<list2>
    <item>
        <field3>cc</field3>
        <field4>valuec</field4>
    </item>
    <item>
        <field3>dd</field3>
        <field4>valued</field4>
    </item>
</list2>

I'm using this xsl but is not working.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>
<xsl:template match="list1/item">
    <list1>
        <xsl:apply-templates select="@*|node()"/>
    </list1>
</xsl:template>
<xsl:template match="list2/item">
    <list2>
        <xsl:apply-templates select="@*|node()"/>
    </list2>
</xsl:template>
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>
<xsl:template match="list1/*">
    <xsl:apply-templates select="node()"/>
</xsl:template>
    <xsl:template match="list2/*">
    <xsl:apply-templates select="node()"/>
</xsl:template>

</xsl:stylesheet>

The expected output is this.

<root>
<field>111</field>
<list1>
    <field1>aa</field1>
    <field2>valuea</field2>
</list1>
<list1>
    <field1>bb</field1>
    <field2>valueb</field2>
</list1>
<list2>
    <field3>cc</field3>
    <field4>valuec</field4>
</list2>
<list2>
    <field3>dd</field3>
    <field4>valued</field4>
</list2>

I tried to use the code above but it's returning the xml with no parent tag at all. How is it possibile to do it?


Solution 1:

How about:

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:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="list1 | list2">
    <xsl:apply-templates/>
</xsl:template>

<xsl:template match="item">
    <xsl:element name="{name(..)}">
        <xsl:apply-templates/>
    </xsl:element>
</xsl:template>

</xsl:stylesheet>

Added:

it removes the tag list2 if there's no item in it. How can I leave it there?

Change:

<xsl:template match="list1 | list2">

to:

<xsl:template match="list1[item] | list2[item]">

In XSLT 2.0 you can do:

<xsl:template match="(list1 | list2)[item]">