Do it with xsl using an XslCompiledTransform, but make sure you cache the XslCompiledTransform because the compilation is slow, execution is extremely fast.
So:
- Write an xsl that matches your xml, sorts them and had the sorted list as output
- Get the XslCompiledTransform holding that xsl from cache, and if it doesn't exist, create it and insert into cache
- Transform your xml through your xsl into a new XmlDocument
This is bloody fast, keeps your code clean and you're flexible when it comes to changing the sort implementation; it's just editing a single xsl.
I type this without checking it so there may be typo's but this is how you should go about:
XslCompiledTransform xsl = (XslCompiledTransform)HttpRuntime.Cache.Get("my_xsl");
if (xsl == null)
{
string fileName = "path/to/your/xslfile.xsl";
xsl = new XslCompiledTransform();
xsl.Load(fileName);
HttpRuntime.Cache.Insert("my_xsl", xsl, new CacheDependency(new string[]{fileName}));
}
And to transform use a method somewhere like this:
public static XmlNode TransformToXml(IXPathNavigable xml, XslCompiledTransform xsl, XsltArgumentList arguments, XmlWriterSettings settings)
{
XmlDocument output = new XmlDocument();
using (XmlWriter writer = XmlWriter.Create(output.CreateNavigator().AppendChild()))
{
xsl.Transform(xml, arguments, writer);
}
return output;
}