How to populate XDocument from String in C#?

XML is a self-describing language that provides data along with rules to identify what information it contains. The XDocument class in C# contains all the information necessary for a valid XML document, including XML declarations, processing instructions, and comments.

The XDocument class is available in the System.Xml.Linq namespace and derives from XContainer, allowing it to contain child nodes. However, XDocument objects can have only one child XElement node, reflecting the XML standard that permits only one root element per document.

Syntax

Following is the syntax to populate XDocument from a string using XDocument.Parse()

XDocument xml = XDocument.Parse(xmlString);

Following is the syntax to load XDocument from a file using XDocument.Load()

XDocument xml = XDocument.Load(filePath);

Using XDocument.Parse() Method

The XDocument.Parse() method converts an XML string directly into an XDocument object. This is the most common approach when working with XML data stored as strings −

Example

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.WriteLine("XDocument created successfully!");
         Console.WriteLine("Root element: " + xml.Root.Name);
         Console.WriteLine("Number of departments: " + xml.Root.Elements().Count());
         
         Console.WriteLine("\nDepartments:");
         foreach (XElement department in xml.Root.Elements()) {
            Console.WriteLine("- " + department.Value);
         }
      }
   }
}

The output of the above code is −

XDocument created successfully!
Root element: Departments
Number of departments: 4

Departments:
- Account
- Sales
- Pre-Sales
- Marketing

Using XDocument.Load() Method

The XDocument.Load() method reads XML content from a file and creates an XDocument object. This approach is useful when XML data is stored in external files −

Example

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

namespace DemoApplication {
   public class Program {
      public static void Main() {
         // Create a sample XML file first
         string xmlContent = @"<Employees>
            <Employee id='1'>
               <Name>John Doe</Name>
               <Position>Manager</Position>
            </Employee>
            <Employee id='2'>
               <Name>Jane Smith</Name>
               <Position>Developer</Position>
            </Employee>
         </Employees>";
         
         // Write to temporary file
         string tempFile = Path.GetTempFileName();
         File.WriteAllText(tempFile, xmlContent);
         
         // Load XDocument from file
         XDocument xml = XDocument.Load(tempFile);
         Console.WriteLine("XDocument loaded from file successfully!");
         
         foreach (XElement employee in xml.Root.Elements()) {
            string id = employee.Attribute("id").Value;
            string name = employee.Element("Name").Value;
            string position = employee.Element("Position").Value;
            Console.WriteLine($"Employee {id}: {name} - {position}");
         }
         
         // Clean up
         File.Delete(tempFile);
      }
   }
}

The output of the above code is −

XDocument loaded from file successfully!
Employee 1: John Doe - Manager
Employee 2: Jane Smith - Developer

Working with Complex XML Structures

Example

using System;
using System.Xml.Linq;

namespace DemoApplication {
   public class Program {
      public static void Main() {
         string complexXml = @"<Library>
            <Book isbn='978-0321958693' category='Programming'>
               <Title>Effective C#</Title>
               <Author>Bill Wagner</Author>
               <Price>45.99</Price>
            </Book>
            <Book isbn='978-1617294532' category='Programming'>
               <Title>C# in Depth</Title>
               <Author>Jon Skeet</Author>
               <Price>52.99</Price>
            </Book>
         </Library>";
         
         XDocument library = XDocument.Parse(complexXml);
         
         Console.WriteLine("Library Contents:");
         Console.WriteLine("=================");
         
         foreach (XElement book in library.Root.Elements("Book")) {
            Console.WriteLine($"ISBN: {book.Attribute("isbn").Value}");
            Console.WriteLine($"Category: {book.Attribute("category").Value}");
            Console.WriteLine($"Title: {book.Element("Title").Value}");
            Console.WriteLine($"Author: {book.Element("Author").Value}");
            Console.WriteLine($"Price: ${book.Element("Price").Value}");
            Console.WriteLine();
         }
      }
   }
}

The output of the above code is −

Library Contents:
=================
ISBN: 978-0321958693
Category: Programming
Title: Effective C#
Author: Bill Wagner
Price: $45.99

ISBN: 978-1617294532
Category: Programming
Title: C# in Depth
Author: Jon Skeet
Price: $52.99

Comparison of Methods

Method Use Case Performance Error Handling
XDocument.Parse() XML data as string Fast - direct parsing XmlException for invalid XML
XDocument.Load() XML data from files/streams File I/O dependent FileNotFoundException + XmlException

Conclusion

XDocument provides two primary methods to populate XML data: Parse() for string-based XML and Load() for file-based XML. Both methods create fully functional XDocument objects that allow easy manipulation and querying of XML content using LINQ to XML.

Updated on: 2026-03-17T07:04:36+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements