How do you determine the order of nodes?

I have the following XML that is generated by a third-party library:

<PhoneNumbers> <PhoneNumber Key="1">123-456-7890</PhoneNumber> <PhoneNumber Key="2">234-567-8901</PhoneNumber> <PhoneNumber Key="3">345-678-9012</PhoneNumber> </PhoneNumbers> 

The problem is that I should not depend on the values ​​of the Key attribute (a) displayed in order, or (b) starting with 1. Moreover, the latter, but I want this processing to be as safe as possible.

What I need to do is get a list of phone numbers sorted by Key value (ascending). Therefore, using XmlNode.SelectNodes I would like the resulting XmlNodeList contain the PhoneNumber nodes in the correct order, and not in the order in which they appear.

How can this be done with XPath?
Is it possible to do this directly?

If that matters, I am using .NET 2.0.

+7
sorting c # xpath order
source share
4 answers

Xpath itself does not define anything for this.

For C # .NET, this might be what you are looking for: http://social.msdn.microsoft.com/forums/en-US/xmlandnetfx/thread/ba975e0e-e0c7-4868-9acc-11d589cafc70/

+4
source share

The XPathExpression class provides the AddSort method:

http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathexpression.aspx

+4
source share

This is not possible with XPath. If you used XPathDocument , you can use the AddSort method.

However, if you are already using an XmlDocument (and / or should be able to update the XML DOM), it's probably just easy to output the SelectNodes result to a SortedDictionary using the value of the Key attribute as the key value.

+3
source share

Here is an example of how to do this with XPathExpression using the AddSort method already described. XPathExpression is available with .Net 2.0 ( http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathexpression.aspx )

 private static void XmlTest() { XPathDocument results = new XPathDocument(@"c:\temp\temp.xml"); XPathNavigator navigator = results.CreateNavigator(); XPathExpression selectExpression = navigator.Compile("/PhoneNumbers/PhoneNumber"); XPathExpression sortExpr = navigator.Compile("@Key"); selectExpression.AddSort(sortExpr, XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Text); XPathNodeIterator nodeIterator = navigator.Select(selectExpression); int i = 0; while (nodeIterator.MoveNext()) { Console.WriteLine(nodeIterator.Current.Value); i++; } } 
+3
source share

All Articles