How to Convert XDocument to XmlDocument in C# ?

To convert an XmlDocument to XDocument , you can use the CreateReader method of the XDocument and load it in to the XmlDocument.

How to Convert XDocument to XmlDocument in C# ?

using System;
using System.Xml;
using System.Xml.Linq;

namespace ACCode
{
    class Program
    {
        static void Main(string[] args)
        {
            var xmlDocumentobj = new XmlDocument();
            xmlDocumentobj.LoadXml("<Root><User1>Test</User1></Root>");
            var xDocument = ConvertToXDocument(xmlDocumentobj);
            var xmlDocument = ConvertToXmlDocument(xDocument);
            Console.ReadLine();
        }
        // Method to convert XDocument to XmlDocument
        public static XmlDocument ConvertToXmlDocument(XDocument input)
        {
            var xmlDocumentObj = new XmlDocument();
            using (var xmlReader = input.CreateReader())
            {
                xmlDocumentObj.Load(xmlReader);
                return xmlDocumentObj;
            }
            
        }

        // Method to convert the XmlDocument to XDocument
        public static XDocument ConvertToXDocument( XmlDocument input)
        {
            using (var reader = new XmlNodeReader(input))
            {
                reader.MoveToContent();
                return XDocument.Load(reader);
            }
        }

    } 
}
%d bloggers like this: