C# XmlDocument Tutorial 🎯

beginner
15 min

C# XmlDocument Tutorial 🎯

Welcome to our comprehensive guide on using the XmlDocument class in C#! In this tutorial, we'll learn how to work with XML documents using C#, focusing on practical examples and real-world scenarios.

By the end of this lesson, you'll be able to create, read, modify, and write XML files using the XmlDocument class. Let's dive right in!

What is XML? 📝

XML (eXtensible Markup Language) is a markup language used to store and transport data. It's similar to HTML, but while HTML is designed for displaying information, XML is designed for data.

What is XmlDocument in C#? 💡

XmlDocument is a class in C# that provides a complete representation of an XML document in memory. It allows you to navigate, manipulate, and modify the XML tree structure.

Creating an XmlDocument 🎯

Let's start by creating an XmlDocument and adding some XML content to it.

csharp
using System.Xml; XmlDocument doc = new XmlDocument(); // Create a root element XmlElement root = doc.CreateElement("root"); doc.AppendChild(root); // Create some child elements XmlElement child1 = doc.CreateElement("child1"); XmlElement child2 = doc.CreateElement("child2"); root.AppendChild(child1); root.AppendChild(child2); // Create some grandchild elements XmlElement grandchild1 = doc.CreateElement("grandchild1"); XmlElement grandchild2 = doc.CreateElement("grandchild2"); child1.AppendChild(grandchild1); child1.AppendChild(grandchild2); // Print the XML document Console.WriteLine(doc.OuterXml);

Reading an XmlDocument 🎯

To read an XML file, you can use the Load method of the XmlDocument class.

csharp
XmlDocument doc = new XmlDocument(); doc.Load("example.xml"); // Print the XML document Console.WriteLine(doc.OuterXml);

Modifying an XmlDocument 🎯

You can modify an XML document by using various methods provided by the XmlDocument class. For example, to change the value of an element, you can use the SetAttribute or InnerText methods.

csharp
// Modify the value of a child element XmlElement childElement = doc.SelectSingleNode("/root/child1/grandchild1"); childElement.SetAttribute("attribute", "new value"); childElement.InnerText = "new text";

Writing an XmlDocument 🎯

To save an XmlDocument to an XML file, you can use the Save method.

csharp
doc.Save("output.xml");

Quiz Time 🎯

Quick Quiz
Question 1 of 1

What does XML stand for?

Quick Quiz
Question 1 of 1

What does the `XmlDocument` class in C# represent?

Quick Quiz
Question 1 of 1

How do you create a new child element using the `XmlDocument` class?

That's all for this tutorial! We've covered the basics of working with XML documents using the XmlDocument class in C#. In the next tutorial, we'll dive deeper into XML manipulation and explore more advanced techniques. Happy coding! 💡💻