How to open and read XML file in C#

XML, being a self-describing language, not only holds the data within its tags but also provides the necessary rules and specifications to accurately interpret and extract the information it encompasses. When we engage in reading an XML file, we are essentially accessing and extracting the data that resides within the designated XML tags present in the file.

C# XML Parser

In the previous program, we successfully created an XML file named "products.xml". Now, in the subsequent C# program, we focus on reading the contents enclosed within the XML tags of that file. Reading an XML file offers various approaches, each tailored to specific requirements. In this particular program, we opt for a node-wise content extraction strategy. To accomplish this, we utilize the XmlDataDocument Class, which provides the necessary functionalities for parsing and retrieving data from an XML file. Within this program, the XmlDataDocument Class efficiently navigates through the XML structure, searching for desired nodes and their corresponding child nodes, extracting the pertinent data present within those child nodes.

Click here to download the input file : product.xml

How to read XML file from C#

using System; using System.Data; using System.Windows.Forms; using System.Xml; using System.IO; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { XmlDataDocument xmldoc = new XmlDataDocument(); XmlNodeList xmlnode ; int i = 0; string str = null; FileStream fs = new FileStream("product.xml", FileMode.Open, FileAccess.Read); xmldoc.Load(fs); xmlnode = xmldoc.GetElementsByTagName("Product"); for (i = 0; i <= xmlnode.Count - 1; i++) { xmlnode[i].ChildNodes.Item(0).InnerText.Trim(); str = xmlnode[i].ChildNodes.Item(0).InnerText.Trim() + " " + xmlnode[i].ChildNodes.Item(1).InnerText.Trim() + " " + xmlnode[i].ChildNodes.Item(2).InnerText.Trim(); MessageBox.Show (str); } } } }

Reading Xml with XmlReader

The XmlReader is a powerful tool that enables the opening and parsing of XML files in a highly efficient manner. It presents a faster and more memory-friendly alternative to processing XML data. By utilizing the XmlReader, developers can traverse through the XML content step-by-step, examining the values of individual elements, and seamlessly progressing to the subsequent XML elements. This lower-level abstraction offers granular control over the XML file structure, allowing for precise manipulation and retrieval of data.

C# XML Handling

XmlReader xReader = XmlReader.Create(new StringReader(xmlNode)); while (xReader.Read()) { switch (xReader.NodeType) { case XmlNodeType.Element: listBox1.Items.Add("<" + xReader.Name + ">"); break; case XmlNodeType.Text: listBox1.Items.Add(xReader.Value); break; case XmlNodeType.EndElement: listBox1.Items.Add(""); break; } }

Full Source : Reading Xml with XmlReader

Reading XML with LINQ

You can read Xml file using LINQ also. The following source code shows how to read an XML file using LINQ.

<?xml version="1.0" encoding="utf-8" standalone="yes"?> <root> <Brand name="Brand1"> <product name="Product1" /> <product name="Product2" /> </Brand> <Brand name="Brand2"> <product name="Product3" /> <product name="Product4" /> </Brand> </root>

Copy and paste the above XML code to a trext editor and save it as Product.XML

Source Code:

using System; using System.Windows.Forms; using System.Xml.Linq; using System.IO; using System.Text; namespace WindowsFormsApplication4 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { StringBuilder result = new StringBuilder(); foreach (XElement level1Element in XElement.Load(@"D:\product.xml").Elements("Brand")) { result.AppendLine(level1Element.Attribute("name").Value); foreach (XElement level2Element in level1Element.Elements("product")) { result.AppendLine(" " + level2Element.Attribute("name").Value); } } MessageBox.Show(result.ToString()); } } }

Reading XML with XmlTextReader

C# XML Handling

The XmlTextReader is a robust component that facilitates direct parsing and tokenization of XML data, aligning closely with the XML specification outlined by the W3C (World Wide Web Consortium). It adheres to the XML specification standards, including the implementation of namespaces as specified. The XmlTextReader Class serves as a powerful tool, offering forward-only and read-only access to a stream of XML data. This means that it allows sequential traversal of the XML content, enabling efficient and reliable processing of XML information.

XmlTextReader xmlReader = new XmlTextReader("d:\\product.xml"); while (xmlReader.Read()) { switch (xmlReader.NodeType) { case XmlNodeType.Element: listBox1.Items.Add("<" + xmlReader.Name + ">"); break; case XmlNodeType.Text: listBox1.Items.Add(xmlReader.Value); break; case XmlNodeType.EndElement: listBox1.Items.Add(""); break; } }

Full Source : Reading Xml with XmlReader

Using XPath with XmlDocument

The XmlDocument class plays a crucial role in XML processing by loading the entire XML content into memory, thereby enabling comprehensive navigation and manipulation of the XML data. It provides developers with the flexibility to traverse the XML document both backward and forward, empowering them to efficiently explore the XML structure. Moreover, XmlDocument facilitates advanced querying capabilities through the integration of XPath technology. This powerful combination allows for targeted and precise retrieval of specific elements or data within the XML document, enhancing the overall flexibility and versatility of XML data processing.

Click here to download the input file : product.xml

Full Source C#
using System; using System.Data; using System.Xml; using System.IO; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load("d:\\product.xml"); XmlNodeList nodeList = xmlDoc.DocumentElement.SelectNodes("/Table/Product"); string proID = "", proName = "", price=""; foreach (XmlNode node in nodeList) { proID = node.SelectSingleNode("Product_id").InnerText; proName = node.SelectSingleNode("Product_name").InnerText; price = node.SelectSingleNode("Product_price").InnerText; MessageBox.Show(proID + " " + proName + " " + price); } } } }