Order XmlNodeList based on attribute

I have an XmlNodeList that contains packages (element) from the root of the XML example below. I want to sort an XmlNodeList based on the value of the node attribute. Sorting must be very efficient, every millisecond counts.

Do you have any ideas?

<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 built from elements. I no longer have access to the XmlDocument, just a list of items.

+4
source share
3 answers

I solved the problem in a very non-elegant way:

  • I repeated my XmlNodeList
  • During iteration I retrieved timestamps
  • After extracting timestamp, I added timestamp-XmlElement to SortedDictionary
  • Converted SortedDictionary to list (sortedKeys = sortedByDateDisctionary.Keys.ToList ();)
  • If you need to sort the nodes Descending, sortedKeys.Reverse ();
  • Then nodes can be accessed by sorted keys.
0
source

You should try Linq for XML.

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

You can 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 ); } 
+2
source

note: xml variable is a 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)); 
0
source

Source: https://habr.com/ru/post/1387702/


All Articles