In this post we will learn how to read XML using C# with the help of code sample. In our previous write-up, we initiated with an overview of XML and fashioned a tangible XML document. At present, our aim is to peruse an extant XML file by utilizing the XmlReader category.
For more such topics you can Search or Visit our C# Section , IIS Section & SQL Section too.
Let’s come to the point, to implement this, you require a pre-existing XML document. Besides this, a fundamental comprehension of C# and XML document structures is essential. As such, the structure of my XML file appears as follows:
<?xml version="1.0" encoding="utf-8"?>
<Data>
<OutPutPath>C:\Users\XYZ\OneDrive\Desktop\CC-OutPuts</OutPutPath>
<links>
<url>https://www.abc.com/ScrapPage1</url>
<url>https://www.abc.com/ScrapPage2</url>
<url>https://www.abc.com/ScrapPage3</url>
<url>https://www.abc.com/ScrapPage4</url>
<url></url>
</links>
</Data>
Parent node:
Node “Data” is the parent node in above sample XML.
Child Nodes:
In above XML “OutPutPath” and “url” are the child nodes. We can use below code sample to read these child node data.
//Reading input xml file for URLs and output location.
// path is the complete path of your folder where xml is located.
string strSettingsXmlFilePath = System.IO.Path.Combine(path, "input.xml");
using (XmlReader reader = XmlReader.Create(strSettingsXmlFilePath))
{
while (reader.Read())
{
if (reader.IsStartElement())
{
//return only when you have START tag
switch (reader.Name.ToString())
{
case "url":
string uri = reader.ReadString();
if (uri != "") {
URLList.Add(uri);
}
break;
case "OutPutPath":
OutPutPath = reader.ReadString();
//Console.WriteLine("Name of the Element is : " + reader.ReadString());
break;
}
}
}
}
How above code work:
Thus, we initiate with the utilization of the using() expression. Within that, we have created XmlReader. Subsequently, we allotted a reader stream of an XML document employing the Create() method. Afterwards, we commence reading the XML file and reader.Read() provides the Boolean value signifying whether an XML statement present or not.
See below we can get the value from child node and can use this in our program.
You can check more on Microsoft Learn and for more such topics you can Search or Visit our C# Section too.