Thursday, June 26, 2008

Sorting XML With System.Xml.XPath.XPathExpression

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("5361");

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);

}

}