Dynamic XML Sorting using LINQ
How can I sort dynamic XML using LINQ having following precedences:
- Sort by node-name
- Sort by node-value
- Sort by attribute-name
- So开发者_StackOverflowrt by attribute-value
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.
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"),
};
精彩评论