How to populate XDocument from String in C#?


XML is a self-describing language and it gives the data as well as the rules to identify what information it contains. Like HTML, XML is a subset of SGML - Standard Generalized Markup Language.

The XDocument class contains the information necessary for a valid XML document. This includes an XML declaration, processing instructions, and comments.

Note that we only have to create XDocument objects if we require the specific functionality provided by the XDocument class. In many circumstances, we can work directly with XElement. Working directly with XElement is a simpler programming model.

XDocument derives from XContainer. Therefore, it can contain child nodes. However, XDocument objects can have only one child XElement node. This reflects the XML standard that there can be only one root element in an XML document. The XDocument is available in System.Xml.Linq namespace.

Example

Let us consider below string which is in XML format and need to be populated as XML.

<Departments>
   <Department>Account</Department>
   <Department>Sales</Department>
   <Department>Pre-Sales</Department>
   <Department>Marketing</Department>
</Departments>
using System;
using System.Xml.Linq;
namespace DemoApplication{
   public class Program{
      public static void Main(){
         string xmlString = @"<Departments>
            <Department>Account</Department>
            <Department>Sales</Department>
            <Department>Pre-Sales</Department>
            <Department>Marketing</Department>
         </Departments>";
         XDocument xml = XDocument.Parse(xmlString);
         Console.ReadLine();
      }
   }
}

Similarly, if we want to convert a file containing xml to XDocument we can use XDocument.Load(path).

Example

using System;
using System.Xml.Linq;
namespace DemoApplication{
   public class Program{
      public static void Main(){
         string xmlPath = @"D:\DemoXml.txt";
         XDocument xml = XDocument.Load(xmlPath);
         Console.ReadLine();
      }
   }
}

Output

In both the above cases the xmlString is converted to Xdocumet like below.

Updated on: 19-Aug-2020

985 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements