Add to My Yahoo! | Google Reader or Homepage | Add to Windows Live | Add to Windows Live Alerts

Wictor Wilén

Microsoft Certified Master (MCM) - SharePoint 2010 | Microsoft Most Valuable Professional (MVP) - SharePoint Server MVP | Author

How to sort XML without XSL in the .NET Framework

Posted at 2008-05-12 08:26 by Wictor Wilén in .NET , C# , XML with 8 comments.

I have several times needed a way to sort XML, retrieved from a file or a web service, inline without invoking XSL transformations, which is the most common way to do it as I have seen.

The .NET Framework contains the System.Xml.XPath namespace and is available from the .NET Framework 1.1 and up. This namespace contains a number of classes which can improve the performance of your .NET classes when working with XML. Specifically the System.Xml.XPath.XPathExpression contains a method (System.Xml.XPath.XPathExpression.AddSort) to sort the XPath query results.

The code below shows you an easy way to sort your XML data based on this namespace.

This is the XML we will use:

<Entries>
  <Entry id="1">
    <Name>Hello</Name>
  Entry>
  <Entry id="2">
    <Name>World</Name>
  </Entry>
  <Entry id="3">
    <Name>Test</Name>
  </Entry>
</Entries>

To sort this based on the Name element all we have to do is to create an XPathNavigator and add an XPath Expression with sorting like this:

XmlDocument doc = new XmlDocument();
doc.Load(@".\data.xml");
XPathNavigator navigator = doc.CreateNavigator();
XPathExpression expression = navigator.Compile("Entries/Entry");
expression.AddSort("Name", XmlSortOrder.Ascending, XmlCaseOrder.UpperFirst, 
string.Empty, XmlDataType.Text);
XPathNodeIterator iterator = navigator.Select(expression);
foreach (XPathNavigator item in iterator) {
    Console.WriteLine(item.Value);               
}

As you can see we create the XPathNavigator from the XmlDocument using the CreateNavigator method (which can be found on XmlNode and derivatives as well) and the create the expression with the sort and executes it using the Select method. Really simple!

To sort on the id attribute we change the AddSort method call to this:

expression.AddSort("@id", XmlSortOrder.Ascending, XmlCaseOrder.UpperFirst, 
string.Empty, XmlDataType.Number);

Notice the XmlDataType.Number value of the last parameter.

The sample above will work on the .NET Framework 2.0 and above, since it uses the GetEnumerator() method of the XPathNodeIterator class, which was introduced in 2.0.

To make it work in .NET 1.1 rewrite the foreach statement with something like this:

...
XPathNodeIterator iterator = navigator.Select(expression);
while(iterator.MoveNext()) {
    Console.WriteLine(iterator.Current.Value);               
}

Hope this one will help you doing crazy workarounds...

Update:  changed typo in .NET 1.1. code sample...

Comments and trackbacks

#  excellent logic by Arun.V.Iyer
Screenshot from websnpr Hi, your logic solved a major problem for me. Thanks a lot. Expect more logics from you.
#  Re: excellent logic by Wictor
Screenshot from websnpr Thanks. Whenever I find some interesting I'll post it fir sure...
#  Excellent work by robert.t.lee
Screenshot from websnpr It saves me lot of time in sorting xml files which were generated on mainframe.
#  Hi by Vinay Bansal
Screenshot from websnpr thanks Yaar it's work
#  Sorting & saving an XML data file by John Long
Screenshot from websnpr I need to sort an XML data file and then save the sorted version of the XML file to disk. Can you supply a sample of how to do this? Thanks, John Long john@TheLongs.us
#  IClOAevOcevoVFKbZQw by necngbxk
Screenshot from websnpr Q9xDe0 dfvfbwldibed, [url=http://ihijrqnkmslt.com/]ihijrqnkmslt[/url], [link=http://lkzgdqoxpgpe.com/]lkzgdqoxpgpe[/link], http://xjncvikpqmat.com/
#  does not work in my case by rk
Screenshot from websnpr Hi there i've complex XMl file and tried what you suggested but unfortunately it does seem to sort! iterator always returns 0 rows! but i dont get any exceptions though. how do you troubleshoot such a case ? BTW your sample file worked but not mine! any advise much appreciated
#  does now sort of by tk
Screenshot from websnpr It seems that namespace need to be specified (setcontext method on XPathExpression) for it to work and now my iterator lists the entities i need. But sorting still does not work! need to investigate more on this.
Make a comment on this post:
Subject:  

Your name:  
Your Url:  
Note: submissions may have to be approved before being visible, so don't submit your comment multiple times.