I have a XDocument where I\'d like to sort all of the elements alphabetically. Here\'s a simplified version of the structure:
Here is an updated example that will include all attributes when performing the sort.
private static XElement Sort(XElement element)
{
XElement newElement = new XElement(element.Name,
from child in element.Elements()
orderby child.Name.ToString()
select Sort(child));
if (element.HasAttributes)
{
foreach (XAttribute attrib in element.Attributes())
{
newElement.SetAttributeValue(attrib.Name, attrib.Value);
}
}
return newElement;
}
private static XDocument Sort(XDocument file)
{
return new XDocument(Sort(file.Root));
}
This post helped me a lot, because I did not want to perform an XML sort using XSLT since I did not want to reformat the XML. I searched all around for a simple solution to perform an XML sort using C# and ASP.NET and I was delighted when I found this thread. Thanks to all, this did exactly what I needed.