Ordering by attribute XML file with nested elements

I would like to order my XML file, but I'm having troubles in understanding how. I noticed that a lot of suggestions are similar to this case.

 var bookstore = xDoc.Element("bookstore")
            .Elements("book")
            .OrderByDescending(s => (int) s.Attribute("id")); 

My XML is made like this:

<?xml version="1.0" encoding="utf-8"?>
<rank>
<difficulty template="gamer">
 <car type="FormulaA" />
 <car type="FormulaC" />
 <car type="GT2" />
 <car type="FormulaB" />
</difficulty>
<difficulty template="racer">
 <car type="FormulaA" />
 <car type="FormulaC" />
 <car type="GT2" />
 <car type="FormulaB" />
</difficulty>
<difficulty template="pro">
 <car type="FormulaA" />
 <car type="FormulaC" />
 <car type="GT2" />
 <car type="FormulaB" />
 </difficulty>
</rank>

I would like to modify it so that the final result is similar to this one, then write it again to the same file.

<?xml version="1.0" encoding="utf-8"?>
<rank>
<difficulty template="gamer">
 <car type="FormulaA" />
 <car type="FormulaB" />
 <car type="FormulaC" />
 <car type="GT2" />
</difficulty>
<difficulty template="racer">
 <car type="FormulaA" />
 <car type="FormulaB" />
 <car type="FormulaC" />
 <car type="GT2" />
</difficulty>
<difficulty template="pro">
 <car type="FormulaA" />
 <car type="FormulaB" />
 <car type="FormulaC" />
 <car type="GT2" />
 </difficulty>
</rank>

I tried to sort those elements with this code, but it doesn't give me the result I want.

XDocument xDoc = XDocument.Load(xmlFile);
var orderedXmlFile = xDoc.Descendants("car").OrderBy(s => (string)s.Attribute("type"));

XDocument doc = new XDocument(new XElement("rank"), orderedXmlFile);
doc.Save(xmlFile);

orderedXmlFile becomes a list similar to

<car type="FormulaA" />
<car type="FormulaA" />
<car type="FormulaA" />
<car type="FormulaB" />
<car type="FormulaB" />
<car type="FormulaB" />
<car type="GT2" />
<car type="GT2" />
<car type="GT2" />

and then I'm unable to save the file. This is the first time I'm trying to modify xml files in C#, so I'll gladly take any advice or suggestions you'd want to give me.

Jon Skeet
people
quotationmark

You're not really trying to order all the car elements - you're trying to order each group of elements. It's probably simplest just to use ReplaceNodes for each difficulty element:

foreach (var difficulty in xDoc.Root.Elements("difficulty"))
{
    difficulty.ReplaceNodes(difficulty.Elements()
                                      .OrderBy(x => (string) x.Attribute("type")));
}

Then just save xDoc again.

This assumes you don't mind modifying your existing XDocument, of course.

people

See more on this question at Stackoverflow