Working with XML Using C#

Introduction

The Extensible Markup Language (XML) is a simple text-based format for representing structured information: documents, data, configuration, books, transactions, invoices, and much more.

It is a very common format and In this post, we will learn some of the basic ways to work with XML in C#.

Getting Started

XDocument and XElement are the the main classes for dealing with XML in .NET .

  • XDocument represents a complete valid XML document.
  • XElement represents an XML element or elements.

LINQ to XML queries are also very popular when working with XML.

For demos, I’ve created a new project using .NET Core Console Template. I’ve also setup a git repository for the C# code which we will see in this post.

Build XML in Code

Lets see a very basic example of creating XML in code:

As you can see that it is very easy to create XML using XDocument constructor. We can add declarations, comments, elements, attributes etc.

Now, lets add some more code to our example:

As, you can see in the code example above that XElement constructor allows to add other XElement(s) and this way we can easily create required XML structure using code.

Saving XML to File

We can use Save method on XDocument to save the XML to file as shown below:

Loading a Document

We can load and read an XML document from file system using XDocument.Load(filePath) method as shown below:

Attribute Based Approach

If we want attribute based approach for our XML, we can use the following code for this purpose:

Query XML

I have updated the code to create the following XML:

As you can see that this file contains data about devices. Now, for your purposes, it could be product data, configuration data etc.

In the following code, we are reading this xml and then using LINQ to query the xml data for certain values. In this example, we are checking for the device record with id value of 10 and then we are reading the Status attribute value of that record:

As you can see that console output is showing the corresponding value as expected.

Summary

This was a very basic introduction of XML and we saw that .NET provides very simple ways to work with XML and makes it very easy to create, read and query the XML data in our applications.

You can download the source code form this git repository.

Let me know if you have some comments or questions. Till next time, Happy Coding.


Discover more from Hex Quote

Subscribe to get the latest posts sent to your email.

1 thought on “Working with XML Using C#”

Comments are closed.

Discover more from Hex Quote

Subscribe now to keep reading and get access to the full archive.

Continue reading