0

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
4
  • 1
    what is dynamic about the XML? can you give us example (small) XML doc to work from? Commented Jun 28, 2011 at 9:56
  • In fact, what does sort mean in this context? Commented Jun 28, 2011 at 9:57
  • @Matt XML will have dynamic nodes, dynamic their values and their order. The XML data is unidentfied. There are hundreds of patterns of data. Commented Jun 28, 2011 at 10:00
  • Your question should be refined: the attributes have no order, thus has no sense to sort by something is not ruled. Commented Jun 28, 2011 at 11:44

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

@Brian I won't be sure about the nodes. XML is a response xml which will be dynamic.
I think you can take the initial doc as just an example XML. The rest of the code will work with any XML document.
@Ramiz Uddin: These examples make no assumption about the names of the nodes. If you need more, you need to be more specific.
@Brian will that sort be nested?
No. You didn't ask for a nested sort. Consider using Descendents() instead of Elements()
1
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"),
           };

1 Comment

I'm new to linq. This is exactly what I was looking for. To be able to dynamically pass in the name of the attribute I wanted to sort on. Now to figure out how to dynamically do asc/desc and be able to pass in the number of params to sort on. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.