How to Convert XmlDocument to XDocument in C# ?

Published on February 7, 2016 by abundantcode

Filed under ADO.NET

Last modified February 6, 2016

Print this page

rate 1 star rate 2 star rate 3 star rate 4 star rate 5 star
Your rating: none, Average: 4 (1 votes)

This article have been viewed 6690 times

If you want to convert an XmlDocument to XDocument in C# , you can use the XmlNodeReader which does the conversion for you. Use the MoveToContent method and load it to the XDocument class.

How to Convert XmlDocument to XDocument 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);

            Console.ReadLine();
        }

        // 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);
            }
        }

    } 
}

Leave a Comment


x

You might be Interested in these Posts

How to convert JSON to XML or XML to JSON in C# ?

Below is a sample code snippet demonstrating how you can convert the Json to XML and vice versa in C...

How to Convert a string in JSON.NET to XML in C# ?

You can use the JsonConvert.DeserializeXmlNode method of JSON.NET to convert from the json string to...

How to populate XDocument from a String in C# ?

Want to load or populate XDocument from a string in C# ? . Use the Parse method defined in the XDocu...