Saturday, October 1, 2016

How to Read an xml File using XmlReader

XML :

XML stands for Extensible Markup Language developed by World Wide Web Consortium
which defines a set of rules for encoding documents that is both machine and human
readable. XML is a text based format for storing and transporting data.

XmlReader :

XmlReader provides a fast and non-cached method of reading xml data.
Some important methods of XmlReader are the following :

- Create(String) :
It creates an instance of XmlReader with specified URI.
XmlReader also has create functions with parameters like Stream, TextReader, etc.

- MoveToContent() :
This method checks whether the current node is a content node and if it is not a
content node it navigates to the next content node or end of file.

- IsStartElement() : 
This method calls MoveToContent and checks whether the node is a start tag or
empty element tag.

- MoveToAttribute(Int32) :
This method moves to the attribute with the specified index.

- MoveToAttribute(String) :
This method moves to the attribute with the specified name.

- MoveToElement() :
This method moves to the element that contains the current attribute

- MoveToFirstAttribute() :
This method moves to the first attribute.

- MoveToNextAttribute() :
This method is used to move to the next attribute.

- Read() :
This method reads the next node from the stream.

- ReadContentAsString() :
 This method reads the text of the current position as a String.

- ReadContentAsInt() :
This method reads the text of the current position as an Integer.

Similarly there are functions named ReadContentAsFloat(), ReadContentAsLong(),
ReadContentAsBoolean() etc.

- ReadStartElement() :
This method checks that the current node is an element and if not it moves to the next
node.

ReadEndElement() :
This method checks that the current node is an end tag and if not it moves to the next
node.

- Skip () :
This method skips the children of the current node.

Some important Properties of XmlReader are the following :

- AttributeCount :
This gets the count of the attributes of the current node.

- BaseURI :
This gets the Base URI of the current node.

- Depth :
This gives the depth of the current node in the XML document.

- EOF :
This gets a value indicating whether the reader is at the end of the stream.

- HasAttributes :
This gets a value that shows whether the current node has attributes.

- HasValue :
This gets a value that says whether the current node has value.

- IsEmptyElement :
This gets a value that shows whether the current node is empty.

- Item[Int32] :
This gets the value of the attribute with the specified index of the current node.

- Item[String] :
This gets the value of the attribute with the specified name of the current node.

- NodeType :
This property gets the type of the current node.

- ReadState :
This property gets the state of the reader.

- Value :
This gets the text value of the current node.

Below I will show an example of how to read an XML document named
employee.xml,

Suppose the XML file is as follows :

employee.xml :


<?xml version="1.0" encoding="utf-8" ?>
<company>
    <department dep_name="HR">
        <employee>Amal</employee>
        <employee>Minnu</employee>
    </department>
    <department dep_name="IT">
        <employee>Joy</employee>
        <employee>Lia</employee>
    </department>
</company>

The server side C# code to read the XML document is as follows :

C# Code (.aspx.cs ) :


protected void Page_Load(object sender, EventArgs e)
{
        using (XmlReader reader = XmlReader.Create(Server.MapPath("~/employee.xml")))
        {
            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    case XmlNodeType.Element:
                        Label1.Text += "Node <b>" + reader.Name + "</b> starts <br/>";
                        if (reader.Name == "department")
                        {
                            string dptName = reader["dep_name"];
                            if (dptName != null)
                            {
                                Label1.Text += "  Department name: " + dptName + "<br/>";
                            }
                        }
                        break;
                    case XmlNodeType.Text:
                        Label1.Text += "Employee: "+reader.Value + "<br/>";
                        break;
                    case XmlNodeType.EndElement:
                        Label1.Text += "Node <b>" + reader.Name + "</b> ends <br/>";
                        break;
                }
            }
        }
}

The Output is as following :

Output :



Node company starts
Node department starts
Department name: HR
Node employee starts
Employee: Amal
Node employee ends
Node employee starts
Employee: Minnu
Node employee ends
Node department ends
Node department starts
Department name: IT
Node employee starts
Employee: Joy
Node employee ends
Node employee starts
Employee: Lia
Node employee ends
Node department ends
Node company ends


XmlTextReader :


XmlTextReader also represents a reader that provides fast, forward-only and non-cached
method of reading XML data. Actually XmlReader is the abstract class of XmlTextReader.
From .NET Framework 2.0 onwards, Microsoft recommends to use XmlReader.

There are other methods of reading XML file which I have explained in the next
article.

No comments:

Post a Comment