How to open and read XML files in C# .NET 6 | Pro Code Guide (2024)

In this article, we will learn about how to work with XML files in C# .NET 6 i.e. in particular how to open and read XML files in C# .NET 6. We will look at various options available in C# to work with the XML file.

How to open and read XML files in C# .NET 6 | Pro Code Guide (1)

Table of Contents

Introduction to XML

XML stands for eXtensible Markup Language which is a markup language on lines with HTML but is not limited to predefined tags. In XML you can define your own tags based on your requirements or the data being transferred. XML was created with the purpose of ease of use and storage of self-describing data.

XML is used to store and transport (share) data independent of the hardware and software used to access or transport XML. XML defines a set of rules to store data in both human and machine-readable formats.

When XML is shared with other users then they are able to parse the data stored in the XML due to the set of rules that form the standards for XML syntax.

Although the XML was designed with the document as the main focus but still the XML format data structures are still widely used in web services, particularly in soap-based WCF web services in .NET.

The platform-independent and language-independent feature of XML makes it ideal to exchange data between different programs i.e. you can export data from one application into XML and then import that data into another program through XML.

Structure & Syntax of an XML Document

XML structure is built using tags and in XML these tags are not predefined. User can add their own tags based on the requirements and data contained in the XML document.

XML document should have one root element that is the parent of all the elements in that XML document. Below is an example of a valid XML document in which <Employee> is the root element.

<?xml version="1.0" encoding="UTF-8"?><!-- Employees Data --><Employees> <Employee> <Id>1</Id> <Name>George</Name> </Employee> <Employee> <Id>2</Id> <Name>Mike</Name> </Employee></Employees>

The first line in the XML document begins with the XML declaration <?xml version="1.0" encoding="UTF-8"?> that is not a tag. It is an XML declaration that describes the information about itself i.e. used version and encoding in the XML document. If this declaration exists on the XML document then it should come first in the document.

UTF-8 is the default character encoding in the XML documents. Encoding of the XML document should be specified to avoid any errors.

You can specify comments in the XML document using the syntax <!-- Comments -->

<Employees> is the tag begins with < & ends with >. Tags can be of three types

  • <Employees> – Start or open Tag
  • </Employees> – Closing or End Tag
  • <Employees /> – Empty Tag

In an XML document, it is mandatory to specify the closing tag, If you don’t specify the end tag then it will invalidate the XML document. XML tags are case sensitive so the case of opening and closing tags should be the same.

All the elements in the XML document should be properly nested i.e. <Employees><Employee><Name>George</Name><Employees><Employee> is invalid XML as it is not properly nested.

You can also specify attributes in the XML element. These attributes are like name-value pairs and these attribute’s values should always be wrapped around in quotes. Below is the same XML document with attributes for the Employee Tag

<?xml version="1.0" encoding="utf-8" ?><!-- Employees Data --><Employees><Employee Id="1"><Name>George</Name></Employee><Employee Id="2"><Name>Mike</Name></Employee></Employees>

If you have an XML document with an element that contains < or > in the data then this XML document will become invalid as the XML parser will interpret these angle brackets as starting or end of the element. To handle data with these XML syntaxes we can use Entity References

There are 5 pre-defined entity references that can be used in an XML document

  1. < (less than) – &lt;
  2. > (greater than) – &gt;
  3. & (ampersand) – &amp;
  4. ‘ (apostrophe) – &apos;
  5. ” (quotation mark) – &quot;

The Entity References can be used in the XML document as shown below

<?xml version="1.0" encoding="utf-8" ?><Employees> <Employees> <SalaryRange>&lt; 5000</SalaryRange> </Employee></Employees> 

So far we have learned about the introduction to XML and XML structure now let’s learn about different ways how we can open and read XML files in C# .NET 6

Open and read XML files in C# .NET 6

For demonstration purposes, we will create a project of the type Console App targetting .NET 6 with the name ProCodeGuide.Samples.XMLParser. I am using Visual Studio Community 2022 version 17.2.0

We will create an XML document EmployeeData.xml with the structure as shown below.

<?xml version="1.0" encoding="utf-8" ?><!-- Employees Data --><Employees><Employee><Id>1</Id><Name>George</Name></Employee><Employee><Id>2</Id><Name>Mike</Name></Employee><Employee><Id>3</Id><Name>Sam</Name></Employee><Employee><Id>4</Id><Name>Eric</Name></Employee><Employee><Id>5</Id><Name>Cathy</Name></Employee></Employees>

We will add this XML file to our console app project and in properties for this XML file, we will set the value for property Copy to Output Directory as Copy always and we will try to open and read this XML file in our C# .NET Console App project.

Using the above XML file we will learn about multiple ways available to open and read XML files in C# .NET 6

Read XML File using XMLDocument

In this approach, we will make use of the XMLDocument class available in the System.Xml namespace to load the complete XML file into the object. Then make use of the method SelectNodes to fetch all the nodes for <Employee> from the XML file into the XmlNodeList class.

Once all the nodes from the XML file have been fetched then we loop through the nodes available in XmlNodeList and print the value for each node.

We will make use of the method SelecSingleNode to select the node from the XmlNodeList and then make use of the InnerText property to read the value of the selected node to print the same in the console.

Below is the code which makes use of XMLDocument to read the EmployeeData.xml file

internal static void ReadXMLFileUsingXMLDocument(){ XmlDocument xmlDcoument = new XmlDocument(); xmlDcoument.Load(@"EmployeeData.xml"); XmlNodeList? xmlNodeList = xmlDcoument.DocumentElement.SelectNodes("/Employees/Employee"); Console.WriteLine("Output using XMLDocument"); foreach (XmlNode xmlNode in xmlNodeList) { Console.WriteLine("Id of the Employee is : " + xmlNode.SelectSingleNode("Id").InnerText); Console.WriteLine("Name of the Employee is : " + xmlNode.SelectSingleNode("Name").InnerText); Console.WriteLine(); }}

After execution of the above code, we get the below output

How to open and read XML files in C# .NET 6 | Pro Code Guide (2)

Read XML File using XMLReader

In this approach, we make use of the XmlReader class available in the namespace System.Xml to read the EmployeeData.xml file. We have made use of the Create method in the XmlReader class to assign the stream of the XML file.

XMLReader as compared to XMLDocument consumes less memory and is even a faster alternative to open and read XML files in C# .NET. It is an approach in which one element is read at a time and then it moves to the next element. So instead of loading the complete XML document in memory, it processes one element at a time.

Next, we will make use of the Read method in the XmlReader class to read the XML File and we will be using this in the while loop as the Read method returns a boolean true till there is an XML statement to read from the file i.e. we will loop till the last XML statement in the XML file.

After the XML statement is read using the Read method we check if the statement is the starting element and if it is the starting element then we check if it’s Id or Name using the property Name in the XmlReader class accordingly we print the value for Id or Name element using ReadString method to read the value for the current element.

Below is the code which makes use of the XMLReader class to read the EmployeeData.xml file

internal static void ReadXMLFileUsingXMLReader(){ using (XmlReader xmlReader = XmlReader.Create(@"EmployeeData.xml")) { Console.WriteLine("Output using XMLReader"); while (xmlReader.Read()) { if (xmlReader.IsStartElement()) { switch (xmlReader.Name.ToString()) { case "Id": Console.WriteLine("Id of the Employee is : " + xmlReader.ReadString()); break; case "Name": Console.WriteLine("Name of the Employee is : " + xmlReader.ReadString()); Console.WriteLine(""); break; } } } }}

After execution of the above code, we get the below output

How to open and read XML files in C# .NET 6 | Pro Code Guide (3)

Read XML Files using LINQ

LINQ can also be used to open and read XML files in C# .NET.

We have made use of the XElement class to read data from the XML file. The Load method of the XElment class has been used to load the data from the XML file EmployeeData.xml.

After fetching all the data using the Load method the foreach loop has been used to iterate the Employee elements in the XML file. To get all the Employee elements from the XML file the Elements method has been used which returns a collection of the specified elements.

Below is the code which makes use of LINQ to read the EmployeeData.xml file

internal static void ReadXMLFileUsingLINQ(){ Console.WriteLine("Output using LINQ"); foreach (XElement xElement in XElement.Load(@"EmployeeData.xml").Elements("Employee")) { Console.WriteLine("Id of the Employee is : " + xElement.Element("Id").Value); Console.WriteLine("Name of the Employee is : " + xElement.Element("Name").Value); Console.WriteLine(); }}

After execution of the above code, we get the below output

How to open and read XML files in C# .NET 6 | Pro Code Guide (4)

Summary

We learned in this article about different options available i.e. using XMLDocument, XMLReader and LINQ to open and read XML files in C# .NET. The XMLReader is preferred compared to XMLDocument as it is faster and also consumes less memory.

Please provide your suggestions & questions in the comments section below

You can check my other trending articles – Build Resilient Microservices (Web API) using Polly in ASP.NET Core & Microservices with ASP.NET Core 3.1 – Ultimate Detailed Guide

References – open and read XML files in C# .NET

Download Source Code

Here you can download the complete source code for this article demonstrating how to open and read XML files in C# .NET 6

https://github.com/procodeguide/ProCodeGuide.Samples.XMLParser

Hope you found this article useful. Please support the Author

How to open and read XML files in C# .NET 6 | Pro Code Guide (5)

How to open and read XML files in C# .NET 6 | Pro Code Guide (2024)

References

Top Articles
Latest Posts
Article information

Author: Frankie Dare

Last Updated:

Views: 6066

Rating: 4.2 / 5 (73 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Frankie Dare

Birthday: 2000-01-27

Address: Suite 313 45115 Caridad Freeway, Port Barabaraville, MS 66713

Phone: +3769542039359

Job: Sales Manager

Hobby: Baton twirling, Stand-up comedy, Leather crafting, Rugby, tabletop games, Jigsaw puzzles, Air sports

Introduction: My name is Frankie Dare, I am a funny, beautiful, proud, fair, pleasant, cheerful, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.