Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you specify node result order?

Tags:

c#

sorting

xpath

I have the following XML, which is generated by a 3rd-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 issue is that I should not depend on the values of the Key attribute (a) appearing in order, or (b) beginning at 1. More so the latter, but I want this processing to be as safe as possible.

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

How can this be accomplished using XPath?
Is this possible to do it directly?

If it makes a difference, I'm using .NET 2.0.

like image 597
Jon Seigel Avatar asked Jan 11 '10 15:01

Jon Seigel


3 Answers

Xpath itself does not define anything for that.

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

like image 104
Roland Bouman Avatar answered Sep 20 '22 18:09

Roland Bouman


The XPathExpression class provides an AddSort method:

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

like image 41
hackerhasid Avatar answered Sep 18 '22 18:09

hackerhasid


This can't be accomplished with XPath. If you were using an XPathDocument you could use the AddSort method.

However if you are already using XmlDocument (and/or need to be able to update the XML DOM) its probably just a easy to dump the result of SelectNodes into a SortedDictionary using the value of the Key attribute as the Key value.

like image 42
AnthonyWJones Avatar answered Sep 19 '22 18:09

AnthonyWJones