views:

836

answers:

3

I was using an XSL style sheet to do the sorting but it seems to be very slow. Is there a more efficient way?

It is a flat list of nodes, if I convert the nodes to an object and sort in a GenericList would it help?

EDIT I don't need the end result to be XML.

+1  A: 

In my experience, XSL is one of the better ways to go, however, the overall speed is a bit sketchy as you get to working with large input files.

You could roll your own sort, but honestly I don't imagine that it would be any faster.

The only other possible option I can think of is to load into a dataview, or something and sort it there, and return to XML, but that seems like a wrong way to go about it.

EDIT - Based on your added information, YES, I'm quite sure that loading into a list would be much faster.....you would need to try it to double check, but if you need it in another format anyway, you might as well.

Mitchel Sellers
+1  A: 

It might be worth first checking that you're not using an inefficient way of selecting nodes, for example //node.

Matthew Wilson
+1  A: 

Do it with xsl using an XslCompiledTransform, but make sure you cache the XslCompiledTransform because the compilation is slow, execution is extremely fast.

So:

  1. Write an xsl that matches your xml, sorts them and had the sorted list as output
  2. Get the XslCompiledTransform holding that xsl from cache, and if it doesn't exist, create it and insert into cache
  3. 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;
}
Martin Kool