Search code examples
c#xmllinqlinq-to-xml

How do you sort an XDocument parent node based its child?


In C# I am trying to sort an XDocument using OrderByDescending. The goal is to read one of the child nodes which contains a date/time stamp and reorder the parent nodes.

I load the XML from a saved file like this:

XDocument Doc = new XDocument();
Doc= XDocument.Load(filename);

Here is an example of my XML:

<KS>
  <Team>   
    <TeamName>Knights</TeamName>
    <TeamColor>blue</TeamColor>
    <LastAccessed>5/9/2013 2:34:22 PM</LastAccessed>
  </Team>
  <Team>
    <TeamName>Rangers</TeamName>
    <TeamColor>red</TeamColor>
    <LastAccessed>5/9/2013 3:49:06 PM</LastAccessed>
  </Team>
  <Team>
    <TeamName>Eagles</TeamName>
    <TeamColor>green</TeamColor>    
    <LastAccessed>5/9/2013 3:50:18 PM</LastAccessed>
  </Team>
</KS>

I would like to reorder <Team> descending based on the child element <LastAccessed>.

I have tried the following without any luck:

var results = Doc.Root.Descendants("Team").OrderByDescending(p => p.Element("LastAccessed"));

XDocument node = new XDocument(Doc.Descendants("KS").OrderByDescending(x => x.Element("Team").Element("LastAccessed").Value.Trim()));

Any suggestions how one would sort XML parent nodes based on a value stored in the child node?


Solution

  • You should have gotten an error that said:

    At least one object must implement IComparable.

    Please always include these errors in your questions.

    You need to provide a child of the Team element that supports the IComparable interface. You need to get the value rather than the XElement that .Elements gives you.

    Change your results line to the below and it will work.

    var results = Doc.Descendants("Team").OrderByDescending(p => DateTime.Parse(p.Element("LastAccessed").Value));