How can I sort dynamic XML using LINQ having following precedences:
- Sort by node-name
- Sort by node-value
- Sort by attribute-name
- Sort by attribute-value
How can I sort dynamic XML using LINQ having following precedences:
Sorting by Node Name:
var doc = XDocument.Parse("<data><carrot /><apple /><orange /></data>");
var sortedByNames = doc.Root.Elements().OrderBy(e => e.Name.ToString());
foreach(var e in sortedByNames)
Console.WriteLine (e.Name);
Sorted by Node Value:
var doc = XDocument.Parse("<data><thing>carrot</thing><thing>apple</thing><thing>orange</thing></data>");
var sortedByValue = doc.Root.Elements().OrderBy(e => e.Value.ToString());
foreach(var e in sortedByValue)
Console.WriteLine (e.Value);
It all follows the same pattern... You sort based on the criteria you define in the selector function passed into the OrderBy method.
doc as just an example XML. The rest of the code will work with any XML document.Descendents() instead of Elements()var data = from item in xmldoc.Descendants("content")
orderby (string)item.Element("title") // by node value
//orderby item.Attribute("something") // by attribute value
select new
{
Title = (string)item.Element("title"),
};