C# XDocument (LINQ) XML Tutorial 🎯

beginner
5 min

C# XDocument (LINQ) XML Tutorial 🎯

Welcome to the C# XDocument (LINQ) XML Tutorial! In this comprehensive lesson, we'll explore how to work with XML data using XDocument and LINQ (Language Integrated Query) in C#. By the end of this tutorial, you'll be able to create, manipulate, and query XML documents with ease.

What is XML? 📝

XML (eXtensible Markup Language) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. It's used to store and transport data, especially when that data needs to be shared between different systems.

What is XDocument? 💡

XDocument is a class in the System.Xml.Linq namespace in C# that represents an XML document. It allows you to work with XML data using LINQ, making it easy to query, manipulate, and transform XML data.

Creating an XML Document with XDocument 📝

To create an XML document using XDocument, you first need to create a new instance of the XDocument class, and then use the Add and AddFirst methods to add elements to the document.

csharp
using System; using System.Xml.Linq; namespace XDocumentExample { class Program { static void Main(string[] args) { var document = new XDocument( new XElement("root", new XElement("item", "Item 1"), new XElement("item", "Item 2") ) ); document.Save("sample.xml"); } } }

In this example, we create an XML document with a root element named "root" and two child elements named "item". The document is then saved to a file named "sample.xml".

Querying an XML Document with LINQ 💡

To query an XML document using LINQ, you can use the XDocument's Descendants and Elements methods. These methods allow you to select specific elements based on their name.

csharp
using System; using System.Linq; using System.Xml.Linq; namespace XDocumentExample { class Program { static void Main(string[] args) { var document = XDocument.Load("sample.xml"); var items = document.Descendants("item"); foreach (var item in items) { Console.WriteLine(item); } } } }

In this example, we load the XML document we created earlier and query it for all elements named "item". We then loop through the resulting collection and print each item to the console.

Manipulating XML Data with XDocument 💡

You can manipulate XML data using XDocument by creating new elements, modifying existing elements, and removing elements.

csharp
using System; using System.Linq; using System.Xml.Linq; namespace XDocumentExample { class Program { static void Main(string[] args) { var document = XDocument.Load("sample.xml"); var newItem = new XElement("item", "New Item"); document.Root.Add(newItem); document.Save("updated.xml"); } } }

In this example, we load the XML document, create a new "item" element, and add it to the root element of the document. We then save the updated document to a new file.

Quiz 🎯

Quick Quiz
Question 1 of 1

What is XML?

Quick Quiz
Question 1 of 1

What is XDocument?