Ramiz Uddin
Ramiz Uddin

Reputation: 4259

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. Sort by attribute-value

Upvotes: 0

Views: 1107

Answers (2)

vvucetic
vvucetic

Reputation: 499

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"),
           };

Upvotes: 1

Brian Genisio
Brian Genisio

Reputation: 48137

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.

Upvotes: 2

Related Questions