How To Open And Read XML File In C# , XmlReader , XmlTextReader ...
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
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); } } } } Next > How to create XML file from Dataset Related Topics- How to XML in C#
- How to create an XML file in C#
- How to create XML file from Dataset
- How to Open and read an XML file to Dataset
- How to create an XML file from SQL
- How to search in a XML file
- How to filter in a XML file
- How to insert data from XML to database
- How to create Excel file from XML
- How to create XML file from Excel
- How to XML to DataGridView
- How to create a TreeView from XML File
- How to create a Crystal Reports from XML File
- XML Serialization Tutorial
- XML Serialization
- XML DeSerialization
Từ khóa » Xml Trong C#
-
Đọc Ghi Dữ Liệu Xml Trong C# - TUAN DC
-
Xử Lý XML Trong C# – Norid's Blog
-
[PDF] C7 - XML Và .NET Trong C#.pptx
-
Đọc Và Ghi XML Với C# – Read And Write XML With C# | For Better Life!
-
[PDF] ĐỌC, GHI XML VỚI C# TRONG ADO.NET
-
Tạo File XML. Thêm, Sửa, Xóa Trên File XML Bằng C# - YouTube
-
XmlDocument Class (System.Xml) - Microsoft Docs
-
[C#] Hướng Dẫn Thêm Xóa Sửa XML File Trong Winform Linq
-
Reading And Writing XML In C# - C# Corner
-
Đọc Ghi XML C# - Read And Write XML With C# | V1.0
-
Đề Xuất 7/2022 # Đọc Ghi Dữ Liệu Xml Trong C# # Top Like
-
Load File XML Bằng C# Và LINQ - ChienTX
-
Đọc, Ghi, Xóa Dữ Liệu XML Trong C#, - Itseovn