开发者

Dynamic XML Sorting using LINQ

How can I sort dynamic XML using LINQ having following precedences:

  1. Sort by node-name
  2. Sort by node-value
  3. Sort by attribute-name
  4. 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"),
           };
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜