How to read and parse an XML file in C#

 Posted on 12/20/2018

Share On: facebook gplus twitter

XML stands for Extensible Markup Language. We can also say that its text based markup language which derived from SGML (Standard Generalized Markup Language).

We can also say its similar like HTML as markup language. XML is designed to store data and you can display that data into web pages. There are limitations also there to store data into XML.

XML uses tags which are not predefined like HTML tags. You need to create your own tags and use to create XML. That means, it’s more like self describing. XML uses Document Type Definition to represent the data, it’s also called DTD.

lets understand xml with one example. Here, we will read and parse xml using C#.

XML File:

<?xml version="1.0" encoding="UTF-8"?>
<age>10 Years</age>
<age>12 Years</age>
<age>13 Years</age>
<age>9 Years</age>

C# to read xml file and display in html.

                XmlDocument xmldoc = new XmlDocument();
                XmlNodeList nodeList = xmldoc.SelectNodes("students");
                string strOutput = "";

                for (int i = 0; i < nodeList.Count; i++)

                    XmlNodeList XMLNode = nodeList[i].ChildNodes;
                    for (int j = 0; j < XMLNode.Count; j++)
                        XmlNodeList SingleXMLNode = XMLNode[j].ChildNodes;
                        strOutput += "First Name: " + SingleXMLNode[0].InnerText + "</br>";
                        strOutput += "Last Name: " + SingleXMLNode[1].InnerText + "</br>";
                        strOutput += "Gender: " + SingleXMLNode[2].InnerText + "</br>";
                        strOutput += "Age: " + SingleXMLNode[3].InnerText + "</br>";
                        strOutput += "Class: " + SingleXMLNode[4].InnerText + "</br>";
                        strOutput += "</br>----------------------------------------</br>";

Fnal Output:

First Name: John
Last Name: Turner
Gender: Male
Age: 10 Years
Class: 5th

First Name: Aidan
Last Name: Walls
Gender: Male
Age: 12 Years
Class: 7th

First Name: Martyn
Last Name: Hills
Gender: Male
Age: 13 Years
Class: 8th

First Name: Jeremy
Last Name: Coester
Gender: Male
Age: 9 Years
Class: 4th


Add Comment: