Fast XmlDocument to XDocument conversion with extension method

Really just a variation based on Kris’ comment on my previous XmlDocument to XDocument conversion post.

So if we like the reader option, what is a convenient way of encapsulating that? Well C# 3 extension methods aren’t too bad.

Here is one way of writing the methods.

public static class XmlDocumentExtensions
public static XDocument ToXDocument(this XmlDocument document)
return document.ToXDocument(LoadOptions.None);

public static XDocument ToXDocument(this XmlDocument document, LoadOptions options)
using (XmlNodeReader reader = new XmlNodeReader(document))
return XDocument.Load(reader, options);

Now, as long as the class is visible to the code you’re writing, you can write code like this.

XmlDocument doc = new XmlDocument();

xdoc = doc.ToXDocument();
var children = xdoc.Document.Element(“parent”).Elements(“child”);
foreach (var child in children)

Of course, if you could you would just start off from an XDocument – this addresses the cases where you already have an XmlDocument around and you can’t just change all code to use XmlDocument.

One thing that I like about extension methods is that it helps bridge dependencies across libraries in a clean way. More on this on some later post.


Comments (0)

Skip to main content