Tuesday, 3 July 2012

.Net Tips : Read XML File With an XMLReader with C# Examples and VB.Net Examples

XmlReader provides fast, forward-only, read-only access to XML documents. These documents may contain various elements in multiple namespaces. XmlTextReader and XmlNodeReader classes derive from XMLReader and work as an abstract class for these classes.
With help of XmlReader Class we can read xml file and also extract data from xml file.
XmlReader class available in System.Xml namespace.
Every .Net Beginners needs to know this.

Here is example of this.
In this example we have "books.xml" file. This file has many books with element <book>. We count books in books.xml and also display xml file's data without xml elements.
In this example we are also taking object of "XmlReaderSettings" Class. With the help of this class we can Ignore Whitespace and Comments using IgnoreWhitespace and IgnoreComments properties to parse XML File.

XML File : (Books.xml)
<?xml version="1.0" encoding="utf-8" ?>
    <Title>SQL Server</Title>

C# Example :
        int intCount = 0;
        XmlReaderSettings objSettings = new XmlReaderSettings();
        objSettings.IgnoreWhitespace = true;
        objSettings.IgnoreComments = true;
        string booksFile = Server.MapPath("books.xml");
        using (XmlReader objReader = XmlReader.Create(booksFile, objSettings))
            while (objReader.Read())
                if (objReader.NodeType == XmlNodeType.Element && "Book" == objReader.LocalName)
                if (objReader.NodeType ==XmlNodeType.Text )
                    Response.Write("<BR />" + objReader.Value);
        Response.Write(String.Format("<BR /><BR /><BR /><b> Total {0} books.</b>", intCount));

VB.net Example :
        Dim intCount As Integer = 0
        Dim objSettings As New XmlReaderSettings()
        objSettings.IgnoreWhitespace = True
        objSettings.IgnoreComments = True
        Dim booksFile As String = Server.MapPath("books.xml")
        Using objReader As XmlReader = XmlReader.Create(booksFile, objSettings)
            While objReader.Read()
                If objReader.NodeType = XmlNodeType.Element AndAlso "Book" = objReader.LocalName Then
                    intCount += 1
                End If
                If objReader.NodeType = XmlNodeType.Text Then
                    Response.Write("<BR />" + objReader.Value)
                End If
            End While
        End Using
        Response.Write([String].Format("<BR /><BR /><BR /><b> Total {0} books.</b>", intCount))

Output :

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.