Question

Am trying to make sorting of data in my XML by attribute "times" and show it in TreeView

I have XML file like

<main>
  <data url="http://www.r.com/" data="13.10.2013 20:16:33" times="6" />
  <data url="https://www.google.com/" data="13.10.2013 20:16:14" times="5" />
  <data url="http://ya.com/" data="13.10.2013 19:21:15" times="26" />
</main>

what i want is to sort all nodes by attribute "times". If i can get any of node (1, 2 or 3), that i can take attribute and compare it with first ono - so can make some sorting. but i can't get required element.

so the question - how can i get any nodes from XML file, if i know only it's serial number or how can i sort XML file by some attribute?

Found, if i have id - i can use simething like

XmlDocument myXml = new XmlDocument();
myXml.Load(myfile);
myXml.GetElementById(`here put id`).GetAttribute("required attribute")

but i havent any id.

EDIT:

<main>
  <data url="http://ya.com/" data="13.10.2013 19:21:15" times="**26**" />
  <data url="http://www.r.com/" data="13.10.2013 20:16:33" times="**6**" />
  <data url="https://www.google.com/" data="13.10.2013 20:16:14" times="**5**" />
</main>
Was it helpful?

Solution

Am new to Linq->Xml, So I have no idea about efficiency in this but it seems to work.

XDocument xdoc = XDocument.Parse(xml);
var ordered = xdoc.Descendants("data")
                  .OrderByDescending(x => int.Parse(x.Attribute("times").Value))
                  .ToArray();
xdoc.Root.RemoveAll();
xdoc.Root.Add(ordered);

OTHER TIPS

Since you want to show data in TreeView,you need to first get all the data from xml and then sort it by times

XDocument doc=XDocument.Load(url);
//extract all data from xml
var data=doc.Descendants("data")
            .Select(x=>
               new
               {
                   url=x.Attribute("url").Value,
                   data=x.Attribute("data").Value,
                   times=int.Parse(x.Attribute("times").Value)
               } 
);

foreach(var datum in data.OrderByDescending(x=>x.times))
{
    datum.url;
    datum.data;
    datum.times;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top