Anon
Anon

Reputation: 173

Group elements in XML

Is it possible using XSLT to group items in an XML file?

Input file:

<start>

<A>
---data---
</A>

<B>
---data---
</B>

<C>
---data---
</C>

<A>
---data---
</A>

<B>
---data---
</B>

</start>

Output should be:

<start>

<A>
---data---
</A>

<A>
---data---
</A>

<B>
---data---
</B>

<B>
---data---
</B>

<C>
---data---
</C>

</start>

How do I do that using XSL? Or is there any better way to do it?

Thanks.

Upvotes: 3

Views: 124

Answers (3)

Jerry
Jerry

Reputation: 46

Yes it is, try this....

<xsl:template match="/">
    <xsl:for-each select="start/*">
        <xsl:sort select="name(.)"/>
        <xsl:element name="{name()}">
            <xsl:value-of select="." />
        </xsl:element>
    </xsl:for-each>
</xsl:template>

Upvotes: 0

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

Sample input:

<start>
    <A>1</A>
    <B>2</B>
    <C>3</C>
    <A>4</A>
    <B>5</B>
</start>

XSLT:

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

    <xsl:template match="start">
        <xsl:copy>
            <xsl:for-each select="*">
                <xsl:sort select="name()"/>

                <xsl:copy-of select="."/>

            </xsl:for-each>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

Output:

<start>
  <A>1</A>
  <A>4</A>
  <B>2</B>
  <B>5</B>
  <C>3</C>
</start>

Upvotes: 6

Anass
Anass

Reputation: 6270

Unlike sorting, grouping is not directly supported in XSLT I think

Upvotes: 0

Related Questions