Parsing XML with the XmlTextReader
XML Parser in C# and VB.Net

XML is a self describing language and it gives the rules as well as the data to parse what data it holds. Parsing (reading) an XML file means that we are parsing the information embedded in XML tags in an XML document. You can parse or read an XML Document in many ways. In this chapter you can see one of the easiest ways to read the XML file.
Parse XML with XmlTextReader in C# and VB.Net
XmlTextReader Class provides forward-only, read-only access to a stream of XML data. The following program demonstrates how to use the XmlTextReader class to read XML (Extensible Markup Language) from a file. XmlTextReader provides direct parsing and tokenizing of XML and implements the XML 1.0 . This program provides fast, tokenized stream access to XML rather than using an object model such as the XML DOM (Document Object Model).
How to read XML file using XmlTextReader
XML File content
1 Product 1 1000 2 Product 2 2000 3 Product 3 3000 4 Product 4 4000
Click here to download Product.xml
Read XML with XmlTextReader in C#
using System; using System.Data; using System.Xml; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { 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("" + xmlReader.Name + ">"); break; } } } } }
C# XML Parser
Output:

Read XML with XmlTextReader in VB.Net

The following VB.Net program parse (read) the XML file (Product.xml) using XmlTextReader and display it in a ListBox.
Imports System.Xml Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim xmlReader As New XmlTextReader("d:\product.xml") While xmlReader.Read() Select Case xmlReader.NodeType Case XmlNodeType.Element listBox1.Items.Add("<" + xmlReader.Name & ">") Exit Select Case XmlNodeType.Text listBox1.Items.Add(xmlReader.Value) Exit Select Case XmlNodeType.EndElement listBox1.Items.Add("" + xmlReader.Name & ">") Exit Select End Select End While End Sub End Class
VB.Net XML Parser
NEXT.....Parse XML - XmlDocument