Converting XDocument to XmlDocument and vice versa

Converting XDocument to XmlDocument and vice versa

Asked on December 20, 2018 in XML.
Add Comment


  • 3 Answer(s)

    Converting XDocument to XmlDocument:

         To convert back and forth use the built in xDocument.CreateReader() and an XmlNodeReader. To make the work easy put that into Extension method.

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

    The source will provide further informations about XmlReader.

     

    Answered on December 20, 2018.
    Add Comment

    Simple code:

         For the convertion process of Xdocument to Xmldocument the below single line code will use,

    XDocument y = XDocument.Parse(pXmldoc.OuterXml); // where pXmldoc is of type XMLDocument
    
    Answered on December 20, 2018.
    Add Comment

    Try  this code:

    using System.Xml;
    using System.Xml.Linq;
     
      #region Extention Method
      public static XElement ToXElement(this XmlElement element)
      {
        return XElement.Parse(element.OuterXml);
      }
     
      public static XmlElement ToXmlElement(this XElement element)
      {
        var doc = new XmlDocument();
        doc.LoadXml(element.ToString());
        return doc.DocumentElement;
      }
      #endregion
    

    The Extention can be done simply using like,

    System.Xml.XmlElement systemXml = (new XElement("nothing")).ToXmlElement();
    System.Xml.Linq.XElement linqXml = systemXml.ToXElement();
    
    Answered on December 20, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.