开发者

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开发者_StackOverflow do it?

Thanks.


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>


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


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>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜