You already have a method to sort the elements. Just apply it recursively:
private static XElement Sort(XElement element)
{
return new XElement(element.Name,
from child in element.Elements()
orderby child.Name.ToString()
select Sort(child));
}
private static XDocument Sort(XDocument file)
{
return new XDocument(Sort(file.Root));
}
Note that this strips all non-element nodes (attributes, text, comments, etc.) from your document.
If you want to keep the non-element nodes, you have to copy them over:
private static XElement Sort(XElement element)
{
return new XElement(element.Name,
element.Attributes(),
from child in element.Nodes()
where child.NodeType != XmlNodeType.Element
select child,
from child in element.Elements()
orderby child.Name.ToString()
select Sort(child));
}
private static XDocument Sort(XDocument file)
{
return new XDocument(
file.Declaration,
from child in file.Nodes()
where child.NodeType != XmlNodeType.Element
select child,
Sort(file.Root));
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…