Tuesday, October 11, 2016

Select XML using XPathNavigator

XPathDocument :


XPathDocument class provides read-only and fast representation of an XML
document using XPath data model. It is contained inside the namespace
System.Xml.XPath.

For navigating through nodes of either XPathdocument or  an XmlDocument,
we can use XPathNavigator class which is initialized using CreateNavigator()
method. XPathNavigator has various methods to select set of nodes using an XPath
expression. If it selects a single node, it is returned in an XPathNavigator object and
in case of set of nodes, it is returned in an XPathNodeIterator object.

I will list some important properties of XPathNavigator :

InnerXml - which gets or sets the mark up of the child nodes of the current node.

OuterXml - which gets or sets the mark up that represents the opening and closing tags
of the current node and its child nodes.

BaseURI - gets the BaseURI of the current node.

HasAttributes - gets a value that tells whether the current node has attributes.

HasChildren - gets a value that tells whether the current node has child nodes.

Value - gets the value of the current item.

ValueAsDouble - gets the value of the current node as a Double.

ValueAsInt - gets the value of the current node as an Int32.

ValueAsLong - gets the value of the current node as an Int64.

ValueAsBoolean - gets the value of the current node as a Boolean.

ValueAsDateTime - gets the value of the current node as a DateTime.

Name - gets the name of the current node.

NodeType - gets the XPathNodeType of the current node.

IsNode - which tells whether the current item is a node.

IsEmptyElement - which tells whether the current node is an empty element
without an end tag.

Some important methods of XPathNavigator are listed below:

CreateAttributes() - This method is used to create new attributes to the current node.

DeleteSelf() - which deletes the current node and its child nodes.

MoveToFirst() - which moves the XPathNavigator to the first sibling of the current node.

MoveToFirstAttribute() - which moves the XPathNavigator to the first attribute of the
current node.

MoveToFirstChild() - which moves the XPathNavigator to the first child node of the current node.

MoveToNext() - which moves the XPathNavigator to the next sibling node of the current node.

MoveToNextAttribute() - which moves the XPathNavigator to the next attribute of the
current node.

MoveToParent() - which moves the XPathNavigator to the parent node of the current node.

MoveToPrevious() - which moves the XPathNavigator to the previous sibling node of the current node.

MoveToRoot() - which moves the XPathNavigator to the root node that the current node belongs to.

ReadSubTree() - This method returns an XmlReader that contains the current node and its
child nodes.

SetValue(String) - Sets the value of the current node with the String specified.

SelectSingleNode(String) - Select a single node in the XPathNavigator using the specified
XPath query.

Select(String) - Select a set of nodes in the XPathNavigator using the specified
XPath query.

Below is an example to read XML data using XPathNavigator.

Suppose there is an XML document as following :

employee.xml :


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

C# code to read XML is as following :

C# Code :


We have to add the following namespace :

using System.Xml.XPath;

protected void Button1_Click(object sender, EventArgs e)
{
        XPathDocument document = new XPathDocument(Server.MapPath("~/employee.xml"));
        XPathNavigator navigator = document.CreateNavigator();
        XPathNodeIterator nodes = navigator.Select("company/department/employee");

        while (nodes.MoveNext())
        {
            Response.Write(nodes.Current.Value +"<br/>");
        }
}

Output :


Amal
Minnu
Anu
Joy
Lia


Code for selecting single node is :


XPathNavigator nav = navigator.SelectSingleNode("company/department/employee");

Response.Write(nav.Value);

This will display the result of first employee node which is Amal

Next I will explain the code using OuterXml and InnerXml of  XPathNavigator.



C# Code :



protected void Button1_Click(object sender, EventArgs e)
{
        XPathDocument document = new XPathDocument(Server.MapPath("~/employee.xml"));
        XPathNavigator navigator = document.CreateNavigator();
       
        string str1 = navigator.OuterXml;

        navigator.MoveToChild(XPathNodeType.Element);
        string str2 = navigator.InnerXml;

}

Here str1 will contain the markup of the entire XML document starting from the
Company node. And str2 contains markup starting from the child of Company
node which is department. 

That is, value of str1 is :

<company>
  <department dep_name="HR">
    <employee>Amal</employee>
    <employee>Minnu</employee>
    <employee>Anu</employee>
   </department>
  <department dep_name="IT">
    <employee>Joy</employee>
    <employee>Lia</employee>
  </department>
</company>

And value of str2 is :

  <department dep_name="HR">
    <employee>Amal</employee>
    <employee>Minnu</employee>
    <employee>Anu</employee>
  </department>
  <department dep_name="IT">
    <employee>Joy</employee>
    <employee>Lia</employee>
  </department>

How to convert an XPathNavigator to an XmlReader? 


XPathNavigator has ReadSubTree method which helps to copy the entire XML or
one node and its child nodes to an XmlReader. Below is the example code:


C# Code :




protected void Button1_Click(object sender, EventArgs e)
{
        XPathDocument document = new XPathDocument(Server.MapPath("~/employee.xml"));

        XPathNavigator navigator = document.CreateNavigator();

        XmlReader reader = navigator.ReadSubtree();

        while (reader.Read())

        {

            string str1 = reader.ReadInnerXml();

        }


        reader.Close();

        navigator.MoveToChild("company","");
        navigator.MoveToChild("department", "");
        navigator.MoveToChild("employee", "");
        XmlReader emp = navigator.ReadSubtree();
        while (emp.Read())
        {
            string str2 = emp.ReadInnerXml();
        }
        emp.Close();
 }

If we execute the above code we can see that the reader object holds markup
starting from company node as ReadSubtree function reads the current node 
and its child nodes. Value of String str1 will be the markup starting from
department node as ReadInnerXml function reads the innerXml of the Company node.

MoveToChild function helps to move to the child node from where the XPathNavigator
is positioned. We can see that the value of String str2 will be the name of the first 
employee which is Amal.

No comments:

Post a Comment