c sharp

How to Read XML in C#

The widely used data format for internet data sharing is XML, as data can be stored in it and exchanged between systems in a flexible and user-friendly fashion. In C#, reading XML files is a common task, and the .NET framework provides various classes and methods for parsing and reading XML files. This post will go over utilizing the.NET framework to read XML in C#.

Reading XML in C#

There are several ways to read an XML file in C# and each method has its advantages and disadvantages, and the choice depends on the requirements of the project. Below are some ways to read an XML file in C#:

Here is the content of the XML file that I have created and will be used for demonstration in coming up methods:

<?xml version="1.0" encoding="utf-8"?>
<employees>
  <employee>
    <id>1</id>
    <name>Sam bosh</name>
    <department>Marketing</department>
    <salary>50000</salary>
  </employee>
  <employee>
    <id>2</id>
    <name>Jane Doe</name>
    <department>Finance</department>
    <salary>60000</salary>
  </employee>
  <employee>
    <id>3</id>
    <name>James</name>
    <department>Human Resources</department>
    <salary>70000</salary>
  </employee>
</employees>

1: Using XmlDocument

To read an XML file in C#, you can use the XmlDocument class or the XDocument class, both of which are part of the System.Xml namespace. The XmlDocument class provides a DOM (Document Object Model) approach for reading XML, whereas the XDocument class provides a LINQ (Language-Integrated Query) approach. Here is an example utilizing the XmlDocument class to read an XML file:

using System;
using System.Xml;

class Program
{
    static void Main(string[] args)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load("employees.xml");

        XmlNodeList nodes = doc.DocumentElement.SelectNodes("/employees/employee");

        foreach (XmlNode node in nodes)
        {
            string id = node.SelectSingleNode("id").InnerText;
            string name = node.SelectSingleNode("name").InnerText;
            string department = node.SelectSingleNode("department").InnerText;
            string salary = node.SelectSingleNode("salary").InnerText;
            Console.WriteLine("ID: {0}, Name: {1}, Department: {2}, Salary: {3}", id, name, department, salary);
        }
    }
}

This code uses the XmlDocument class to load the XML file and the SelectNodes method to retrieve a list of employee nodes. Then, for each employee node, it uses the SelectSingleNode method to retrieve the values of the id, name, department, and salary child nodes and displays them using Console.WriteLine:

2: Using XDocument

Alternatively, you can also use the XDocument class to read an XML file using a LINQ approach, and below is the code that illustrates how to do it:

using System;

class Program
{
    static void Main(string[] args)
    {
        XDocument doc = XDocument.Load("employees.xml");

        foreach (XElement element in doc.Descendants("employee"))
        {
            int id = int.Parse(element.Element("id").Value);
            string name = element.Element("name").Value;
            string department = element.Element("department").Value;
            int salary = int.Parse(element.Element("salary").Value);
            Console.WriteLine($"ID: {id}, Name: {name}, Department: {department}, Salary: {salary}");
        }
    }
}

The XML file is loaded into an XDocument object using the XDocument.Load method. The XML file’s “employee” elements are then all retrieved using the Descendants technique. For each element, its child elements are accessed using the Element method, and their values are extracted using the Value property. Finally, the extracted data is printed to the console.

Note that XDocument belongs to the System.Xml.Linq namespace, so you need to include the following using statement at the top of your C# file

3: Using XmlReader

XmlReader is a fast and efficient way to read an XML file in C#. It reads the file sequentially, which means it only loads one node at a time, making it ideal for working with large XML files that would otherwise be difficult to handle in memory.

using System;
using System.Xml;

class Program
{
    static void Main(string[] args)
    {
        using (XmlReader reader = XmlReader.Create("employees.xml"))
        {
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element && reader.Name == "employee")
                {
                    Console.WriteLine("ID: " + reader.GetAttribute("id"));
                    reader.ReadToDescendant("name");
                    Console.WriteLine("Name: " + reader.ReadElementContentAsString());
                    reader.ReadToNextSibling("department");
                    Console.WriteLine("Department: " + reader.ReadElementContentAsString());
                    reader.ReadToNextSibling("salary");
                    Console.WriteLine("Salary: " + reader.ReadElementContentAsString());
                }
            }
        }
    }
}

In this example, we use XmlReader.Create a method to create an instance of XmlReader and pass the XML file path as a parameter. We then use a while loop to read through the XML file node by node using the Read method of XmlReader.

Inside the loop, we first check if the current node is an employee element using the NodeType and Name properties of XmlReader. If so, we employ the GetAttribute method to retrieve the id attribute’s value.

Next, we use the ReadToDescendant method to move the reader to the name element inside the employee element. The value of the name element is then obtained by using the ReadElementContentAsString function.

Similarly, we use the ReadToNextSibling method to move the reader to the next sibling element and get the value of department and salary elements.

Finally, we use using block to ensure that the XmlReader object is properly disposed of after we finish reading the XML file:

4: XML to LINQ

Reading an XML file using LINQ to XML in C# is a powerful way to access and manipulate XML data. LINQ to XML is a component of the LINQ technology that provides a simple and efficient API for working with XML data.

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

class Program
{
    static void Main(string[] args)
    {
        XDocument doc = XDocument.Load("employees.xml");

        var employees = from e in doc.Descendants("employee")
                        select new
                        {
                            Id = e.Element("id").Value,
                            Name = e.Element("name").Value,
                            Department = e.Element("department").Value,
                            Salary = e.Element("salary").Value
                        };
        foreach (var employee in employees)
        {
            Console.WriteLine($"Id: {employee.Id}, Name: {employee.Name}, Department: {employee.Department}, Salary: {employee.Salary}");
        }
    }
}

In this code, we first load the XML file using the XDocument.Load() method. Then, we use LINQ to XML to query the XML data and select the id, name, department, and salary elements for each employee element. We store this data in an anonymous type and then loop through the results to print the employee information to the console.

5: Using XPath

XPath is a query language that is used to navigate through an XML document to locate specific elements, attributes, and nodes. It is an effective tool for information searching and filtering in an XML document. In C#, we can use the XPath language to read and extract data from XML files.

using System;
using System.Xml.XPath;
using System.Xml;

class Program
{
    static void Main(string[] args)
    {  
        XmlDocument doc = new XmlDocument();
        doc.Load("employees.xml");

        // Create an XPathNavigator from the document
        XPathNavigator nav = doc.CreateNavigator();

        // Compile the XPath expression
        XPathExpression expr = nav.Compile("/employees/employee/name");

        // Evaluate the expression and iterate through the results
        XPathNodeIterator iterator = nav.Select(expr);
        while (iterator.MoveNext())
        {
            Console.WriteLine(iterator.Current.Value);
        }
    }
}

This code loads the “employees.xml” file using an XmlDocument, creates an XPathNavigator from the document, and compiles an XPath expression to select all the <name> elements under the <employee> elements. It then evaluates the expression and iterates through the results, printing out the value of each <name> element.

Note: using XPath can be a powerful and flexible way to select elements and attributes from an XML document, but it can also be more complex than some of the other methods we’ve discussed.

Conclusion

Using the XmlDocument class provides full DOM manipulation capabilities, but it can be slower and more memory-intensive than the other methods. The XmlReader class is a good option for reading large XML files, as it provides a fast, forward-only, and non-cached stream-based approach. The XDocument class provides a simpler and more concise syntax, but it may not be as performant as the XmlReader. Additionally, the LINQ to XML and XPath methods provide powerful querying capabilities to extract specific data from an XML file.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.