Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order XmlNodeList based on an attribute

Tags:

c#

xml

I have an XmlNodeList that contains packets (item) from the root of the XML example below. I want to sort the XmlNodeList based on the node's key attribute value. The sorting has to be very efficient, every millisecond counts.

Do you have any idea?

<root>
    <item key="1000000020">
        Content 20
    </item>
    <item key="1000000001">
        Content 1
    </item>
    ...
    <item key="1043245231">
        Content n
    </item>
</root>

Edit: I already have an XmlNodeList constructed from the items. I do not have access to the XmlDocument anymore, only the list of items.

like image 348
Germstorm Avatar asked Dec 23 '11 08:12

Germstorm


2 Answers

You should try Linq to XML.

 XDocument doc = XDocument.Load(file);

   var nodeList = from ele in doc.Descendants("item")
                   orderby int.Parse(ele.Attribute("key").Value)
                   select ele;

You may try XPathNavigator and XPathExpression.

 //I presume that variable xNodeList contains XmlNodeList.
  XPathNavigator nav=xNodeList.Item(0).OwnerDocument.CreateNavigator();
  XPathExpression exp = nav.Compile("root/item");


  exp.AddSort("@key", XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Number );

  foreach (XPathNavigator t in nav.Select(exp))
  {
    Console.WriteLine(t.OuterXml );
   }
like image 117
KV Prajapati Avatar answered Nov 09 '22 17:11

KV Prajapati


note: xml variable is string value

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

IEnumerable<XmlNode> rows = doc.SelectNodes("report/table/row").Cast<XmlNode>().OrderByDescending(r => Convert.ToDecimal(r.Attributes["conversions"].Value));
like image 36
benc Avatar answered Nov 09 '22 16:11

benc