all groups > dotnet xml > october 2005 >
You're in the

dotnet xml

group:

Sorting an XML document.


Sorting an XML document. Kevin Burton
10/26/2005 5:51:02 PM
dotnet xml: I have a slightly different sorting question than has been proposed before.
My docuement looks like:

<Records>
<Record>
<Sequence>5</Sequence>
<Name>E</Name>
</Record>
<Record>
<Sequence>1</Sequence>
<Name>A</Name>
</Record>
<Record>
<Sequence>4</Sequence>
<Name>D</Name>
</Record>
<Record>
<Sequence>2</Sequence>
<Name>B</Name>
</Record>
<Record>
<Sequence>3</Sequence>
<Name>C</Name>
</Record>
</Records>

Sorted it would look like:

<Records>
<Record>
<Sequence>1</Sequence>
<Name>A</Name>
</Record>
<Record>
<Sequence>2</Sequence>
<Name>B</Name>
</Record>
<Record>
<Sequence>3</Sequence>
<Name>C</Name>
</Record>
<Record>
<Sequence>4</Sequence>
<Name>D</Name>
</Record>
<Record>
<Sequence>5</Sequence>
<Name>E</Name>
</Record>
</Records>

The <Name> node is just some a sample in the real application the <Record>
has a lot of different data. I would like to sort the whole <Record> on
<Sequence>. So every thing that is in the <Record> would move based on the
value of <Sequence> so it is sorted. If I read this in a DOM and user XSLT
conceptually it is just moving nodes around but I end up with a kludgy
algorithm that removes nodes and inserts them and takes too much time. Any
ideas?

Thank you.

Re: Sorting an XML document. Oleg Tkachenko [MVP]
10/27/2005 11:25:34 AM
[quoted text, click to view]

Here is simple XSLT stylesheet that does the job:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="Records">
<Records>
<xsl:apply-templates select="Record">
<xsl:sort select="Sequence" data-type="number"
order="ascending"/>
</xsl:apply-templates>
</Records>
</xsl:template>
<xsl:template match="Record">
<xsl:copy-of select="." />
</xsl:template>
</xsl:stylesheet>


--
Oleg Tkachenko [XML MVP, MCAD]
AddThis Social Bookmark Button