Converting XDocument to XmlDocument and vice versa Converting XDocument to XmlDocument and vice versa xml xml

Converting XDocument to XmlDocument and vice versa


You can use the built in xDocument.CreateReader() and an XmlNodeReader to convert back and forth.

Putting that into an Extension method to make it easier to work with.

using System;using System.Xml;using System.Xml.Linq;namespace MyTest{    internal class Program    {        private static void Main(string[] args)        {            var xmlDocument = new XmlDocument();            xmlDocument.LoadXml("<Root><Child>Test</Child></Root>");            var xDocument = xmlDocument.ToXDocument();            var newXmlDocument = xDocument.ToXmlDocument();            Console.ReadLine();        }    }    public static class DocumentExtensions    {        public static XmlDocument ToXmlDocument(this XDocument xDocument)        {            var xmlDocument = new XmlDocument();            using(var xmlReader = xDocument.CreateReader())            {                xmlDocument.Load(xmlReader);            }            return xmlDocument;        }        public static XDocument ToXDocument(this XmlDocument xmlDocument)        {            using (var nodeReader = new XmlNodeReader(xmlDocument))            {                nodeReader.MoveToContent();                return XDocument.Load(nodeReader);            }        }    }}

Sources:


For me this single line solution works very well

XDocument y = XDocument.Parse(pXmldoc.OuterXml); // where pXmldoc is of type XMLDocument


If you need to convert the instance of System.Xml.Linq.XDocument into the instance of the System.Xml.XmlDocument this extension method will help you to do not lose the XML declaration in the resulting XmlDocument instance:

using System.Xml; using System.Xml.Linq;namespace www.dimaka.com{     internal static class LinqHelper     {         public static XmlDocument ToXmlDocument(this XDocument xDocument)         {             var xmlDocument = new XmlDocument();             using (var reader = xDocument.CreateReader())             {                 xmlDocument.Load(reader);             }            var xDeclaration = xDocument.Declaration;             if (xDeclaration != null)             {                 var xmlDeclaration = xmlDocument.CreateXmlDeclaration(                     xDeclaration.Version,                     xDeclaration.Encoding,                     xDeclaration.Standalone);                xmlDocument.InsertBefore(xmlDeclaration, xmlDocument.FirstChild);             }            return xmlDocument;         }     } }

Hope that helps!