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)
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();
XDocument xdoc = doc.ToXDocument();
var children = xdoc.Document.Element(“parent”).Elements(“child”);
foreach (var child in children)
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.