I want to sort a XML file with LINQ. The XML is below and is only an example. Normally it is much bigger and more complex. The XML should be sorted by title, ascending. Not the whole XML at once, but every parentNode for itself. Leafs are always at the bottom. Folder or non-leafs are at the top. The following XML is already well structured, but the titles are in the wrong order. The sort algorithm should also replace wrong positioned non-leaf nodes.
I have already some code which does the job, but I want to know if there is a more elegant or a shorter way. At the moment I have to call a function recursive to make the traversion. Maybe this can be done in another way.
Thank you.
Rene
Here is my XML:
<Node title="text99" leaf="no">
<Node title="text98" leaf="no">
<Node title="text97" leaf="no">
<Node title="text96" leaf="yes"/>
<Node title="text95" leaf="yes"/>
</Node>
<Node title="text94" leaf="no">
<Node title="text93" leaf="yes"/>
<Node title="text92" leaf="yes"/>
</Node>
<Node title="text91" leaf="yes"/>
<Node title="text90" leaf="yes"/>
</Node>
<Node title="text89" leaf="no">
<Node title="text88" leaf="no">
<Node title="text87" leaf="yes"/>
<Node title="text86" leaf="yes"/>
</Node>
<Node title="text85" leaf="no">
<Node title="text84" leaf="yes"/>
<Node title="text83" leaf="yes"/>
</Node>
<Node title="text82" leaf="yes"/>
<Node title="text81" leaf="yes"/>
</Node>
<Node title="text80" leaf="no">
<Node title="text79" leaf="no">
<Node title="text78" leaf="no">
<Node title="text78" leaf="yes"/>
<Node title="text77" leaf="yes"/>
</Node>
<Node title="text76" leaf="no">
<Node title="text75" leaf="yes"/>
<Node title="text74" leaf="yes"/>
</Node>
<Node title="text73" leaf="yes"/>
<Node title="text72" leaf="yes"/>
</Node>
<Node title="text71" leaf="no">
<Node title="text70" leaf="no">
<Node title="text69" leaf="yes"/>
<Node title="text68" leaf="yes"/>
</Node>
<Node title="text67" leaf="no">
<Node title="text66" leaf="yes"/>
</Node>
<Node title="text65" leaf="yes"/>
<Node title="text64" leaf="yes"/>
</Node>
<Node title="text63" leaf="yes"/>
<Node title="text62" leaf="yes"/>
</Node>
<Node title="text61" leaf="yes"/>
<Node title="text60" leaf="yes"/>
And here is my code:
using (XmlReader reader = XmlReader.Create(XmlStream))
{
XDocument xDoc = XDocument.Load(reader);
Action<XElement> sortXml = null;
sortXml = xElement =>
{
bool sortParentNode = false;
foreach (var xElem in xElement.Elements())
{
if (xElem.HasElements)
{
// go into deep
sortXml(xElem);
}
else
{
// break loop and sort parentNode
sortParentNode = true;
break;
}
}
if (sortParentNode)
{
xElement.ReplaceNodes(from node in xElement.Elements()
orderby node.Attribute("title").Value
group node by node.HasElements into folderGroup
orderby folderGroup.Key descending
select folderGroup);
}
};
sortXml(xDoc.Root);
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…