Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting entire xdocument based on subnodes

I have an xml of the following format:

<?xml version="1.0" encoding="utf-8"?>
<contactGrp name="People">
  <contactGrp name="Developers">
    <customer name="Mike" ></customer>
    <customer name="Brad" ></customer>
    <customer name="Smith" ></customer>
  </contactGrp>
  <contactGrp name="QA">
    <customer name="John" ></customer>
    <customer name="abi" ></customer>
  </contactGrp>
</contactGrp>

I'd like to sort the list of customers based on their names, and return the document in the following format:

<?xml version="1.0" encoding="utf-8"?>
<contactGrp name="People">
  <contactGrp name="Developers">
    <customer name="Brad" ></customer>
    <customer name="Mike" ></customer>
    <customer name="Smith" ></customer>
  </contactGrp>
  <contactGrp name="QA">
    <customer name="abi" ></customer>
    <customer name="John" ></customer>
  </contactGrp>
</contactGrp>

I am using c# and currently xmldocument.

thank you

like image 732
vondip Avatar asked Feb 27 '11 21:02

vondip


1 Answers

You could do something like this

var doc = XDocument.Load(/* ... */);

foreach (var g in doc.Descendants("contactGrp"))
{
    var customers = g.Elements("customer").ToList();
    customers.Remove();
    g.Add(customers.OrderBy(c => c.Attribute("name").Value));
}
like image 98
Josef Pfleger Avatar answered Sep 21 '22 13:09

Josef Pfleger