Sorting XML With System.Xml.XPath.XPathExpression

This question came up twice this week, so I thought it warranted a quick post.  If you want to retrieve a sorted list of nodes from an XmlDocument instance, there are a couple ways to do this.  You can use XSLT, or you can write your own sorting algorithm.  The .NET Framework provides capability to provide sort orders to the result of an xpath query through the System.Xml.XPath.XPathExpression::AddSort method.  Here is a simplistic demo:

static void Main(string[] args)

{

XmlDocument doc = new XmlDocument();

doc.LoadXml("<a><b>5</b><b>3</b><b>6</b><b>1</b></a>");

XPathNavigator nav = doc.CreateNavigator();

string path = "/a/b";

XPathExpression expression = nav.Compile(path);

expression.AddSort("text()", XmlSortOrder.Ascending, XmlCaseOrder.None, string.Empty, XmlDataType.Number);

XPathNodeIterator iterator = nav.Select(expression);

while (iterator.MoveNext())

{

Console.WriteLine(iterator.Current.Value);

}

}

Dan Wahlin maintains an excellent resource site, XML For ASP.NET, to find quick HowTo's on various XML technologies.