Share via


Fast way to convert XmlDocument into XDocument

This question came up in the forums a little while ago, and I thought it might be interesting to do some comparisons.

I first came up with a few ways of turning an XmlDocument into an XDocument.

private

static XDocument DocumentToXDocument(XmlDocument doc)
{
  return XDocument.Parse(doc.OuterXml);
}

private static XDocument DocumentToXDocumentNavigator(XmlDocument doc)
{
  return XDocument.Load(doc.CreateNavigator().ReadSubtree());
}

private static XDocument DocumentToXDocumentReader(XmlDocument doc)
{
  return XDocument.Load(new XmlNodeReader(doc));
}

Next I whipped up a function to time these with something quick and dirty. I make sure the past activity doesn't both much in terms of leaving garbage, and I warm up the action a bit (I also warm up the Stopwatch methods, just in case).

private

static long Time(int count, Action action)
{
  GC.Collect();
  for (int i = 0; i < 3; i++)
{
action();
}

  Stopwatch watch = new Stopwatch();
watch.Start();
watch.Stop();
watch.Reset();
watch.Start();

  for (int i = 0; i < count; i++)
{
action();
}

  long result = watch.ElapsedMilliseconds;
watch.Stop();
  return result;
}

And finally, all together:

StringBuilder

sb = new StringBuilder();
sb.Append("<parent>");
for (int i = 0; i < 1000; i++)
{
sb.Append(" <child>text</child>");
}
sb.Append("</parent>");

string text = sb.ToString();
XmlDocument doc = new XmlDocument();
doc.LoadXml(text);

long docToXDoc = Time(1000, () => DocumentToXDocument(doc));
long docToXDocNavigator = Time(1000, () => DocumentToXDocumentNavigator(doc));
long docToXDocReader = Time(1000, () => DocumentToXDocumentReader(doc)); 

Note that the actual numbers don't matter much, as this is my laptop running a bunch of things in the background, in the debugger and whatnot, but the relative values are interesting to see.

These are the values I got (they vary a bit each run, but not by much).

  • Using OuterXml: 1973 ms.
  • Using a navigator over the document: 1254 ms.
  • Using a reader over the document: 1154 ms.

Not surprisingly, avoiding the creation of a big string just to re-parse it is a big win - save the planet, use less CPU power!

Enjoy!

Comments

  • Anonymous
    March 14, 2009
    Can you use C# 3.0 extension methods for this to make this a bit seamless. Just a thought....

  • Anonymous
    March 14, 2009
    Kris, you're right, that would certainly make the conversion code more discoverable. I've queued up a post with the sample code for that so others can benefit as well. Thanks!