Narabhut
Narabhut

Reputation: 837

Using XSLT to put a wrapping element around XML tags

I have a file like this -

<item>
    <id>5</id>
    <name>Bob</name>
</item>
<item>
    <id>6</id>
    <name>Harry</name>
</item>

I'd like to wrap it around with something like "items" so it looks like this

<items>
    <item>
        <id>5</id>
        <name>Bob</name>
    </item>
    <item>
        <id>6</id>
        <name>Harry</name>
    </item>
</items>

If possible I'd prefer a general solution so it works with tags other than "id" and "name". Is this possible through XSLT?

Upvotes: 2

Views: 710

Answers (2)

hr_117
hr_117

Reputation: 9627

Wrapping element with XSLT in general is not a big deal. But with your input this will not work.

XSLT required well formed XML as input and your XML is not well formed because of the missing top level element.

Upvotes: 3

austin
austin

Reputation: 5876

Not the most creative solution, but it should wrap it.

<xsl:template match="/">
    <items>
        <xsl:apply-templates select="item" />
    </items>
</xsl:template>

<xsl:template match="item">
    <xsl:copy />
</xsl:template>

Upvotes: 0

Related Questions