How to sort an XML file using .NET?

So, you have a third-party web service that likes to abuse XML and return things in order, which makes your programming a complete pain in the neck. For instance...

<file> <node1>Foo</node1> <price>4.99</price> <node2> <key>XX999</key> </node2> </file> 

Here about a thousand are sorted by price.

How can you re-sort this XML document by key value?

I need the result for a sorted XML file. Thanks!

EDIT: .NET version 2.0 (without LINQ)

+4
source share
4 answers

Here's how to do it with XSLT:

Assuming your data takes this form (file.xml):

 <?xml version="1.0"?> <listing> <file> <node1>Foo</node1> <price>4.99</price> <node2> <key>XX999</key> </node2> </file> <file> <node1>Bar</node1> <price>5.67</price> <node2> <key>aa743</key> </node2> </file> <file> <node1>Was</node1> <price>5.67</price> <node2> <key>rr321</key> </node2> </file> </listing> 

This is the conversion (stylesheet.xsl):

 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:strip-space elements="*"/> <xsl:output method="xml" indent="yes"/> <xsl:template match="listing"> <xsl:copy> <xsl:apply-templates select="file"> <xsl:sort select="node2/key" data-type="text"/> </xsl:apply-templates> </xsl:copy> </xsl:template> <xsl:template match="@* | node()"> <xsl:copy> <xsl:apply-templates select="@* | node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet> 

When used with this .NET code (you must add using System.Xml;):

 XslCompiledTransform xslt= new XslCompiledTransform(); xslt.Load(@"c:\stylesheet.xsl"); xslt.Transform(@"C:\file.xml", @"c:\sorted.xml"); 

The results of this output in the sorted.xml file:

 <?xml version="1.0" encoding="utf-8"?> <listing> <file> <node1>Bar</node1> <price>5.67</price> <node2> <key>aa743</key> </node2> </file> <file> <node1>Was</node1> <price>5.67</price> <node2> <key>rr321</key> </node2> </file> <file> <node1>Foo</node1> <price>4.99</price> <node2> <key>XX999</key> </node2> </file> </listing> 
+11
source

Use an Xml stylesheet to convert the source XML to an XML format suitable for your use. You can easily sort items by values ​​during xsl conversion.

+3
source

XSLT rules, of course, but I would go with LINQ To XML (i.e. in the System.Xml.Linq namespace). In particular, you need to do something like this:

 newElement = new XElement(oldElement.Elements().OrderBy(x => x.Whatever); 
+1
source

Will Linq to XML handle this for you?

0
source

All Articles