April 29, 2014

Convert between XDocument and XmlDocument

In one of the applications I was working, I noticed that as we have developed the application we have used both System.Xml and System.Xml.Linq namespaces. Now this can happen for a number of reasons including that as the application got developed, the new namespaces were used but the old code has not been refactored and it's not a priority as well as the latest .NET framework supports it. However, sometimes we might need to convert files from old to new version and vice versa. In my situation, I had to convert XDocument to XmlDocument and vice versa. To cater for this requirement I wrote a class with static methods that perform the conversion taking advantage of the XmlNodeReader and XmlReader classes.

Here's the sample code of the class.

XDoc to XmlDoc
  1. public class XmlConversion
  2. {
  3.     public static XmlDocument ToXmlDocument(XDocument xdoc)
  4.     {
  5.         var xmlDocument = new XmlDocument();
  6.         using (var reader = xdoc.CreateReader())
  7.         {
  8.             xmlDocument.Load(reader);
  9.         }
  10.         return xmlDocument;
  11.     }
  13.     public static XDocument ToXDocument(XmlDocument xmlDoc)
  14.     {
  15.         using (var reader = new XmlNodeReader(xmlDoc))
  16.         {
  17.             reader.MoveToContent();
  18.             return XDocument.Load(reader);
  19.         }
  20.     }
  21. }


Reference: Shahed Kazi at AspNetify.com