top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to Convert XDocument to XmlDocument in C# ?

–1 vote
1,441 views
How to Convert XDocument to XmlDocument in C# ?
posted Jun 9, 2016 by Sathyasree

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

0 votes
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);
            }
        }

    } 
}
answer Jun 9, 2016 by Shivaranjini
0 votes

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

**

answer May 31, 2019 by Rushabh Verma R.
...