Sunday 2 February 2014

XPath Expression to Access or Read XML document in ASP.Net

W3C has developed a new querying language called XPath expression through which we can easily walk into a XML document and select a node. In simple terms, XPath is simple and easily understandable expressions which we can use to select XML node or nodes in an XML document.


To understand this article, we will use the below XML document named Employees.xml and stored in App_Data folder under root directory. 

<?xml version="1.0" encoding="utf-8"?>
<Employees>
  <Employee type="Permanent">
    <ID>100</ID>
    <FirstName>Rakesh</FirstName>
    <LastName>Kumar</LastName>
    <Dept>Software Development</Dept>
  </Employee>
  <Employee type="Contract">
    <ID>101</ID>
    <FirstName>Radha</FirstName>
    <LastName>Jha</LastName>
    <Dept>Software Development</Dept>
  </Employee>
  <Employee type="Permanent">
    <ID>102</ID>
    <FirstName>Richa</FirstName>
    <LastName>Kumari</LastName>
    <Dept>Sales</Dept>
  </Employee>
  <Employee type="Contract">
    <ID>103</ID>
    <FirstName>Santosh</FirstName>
    <LastName>Kumar</LastName>
    <Dept>HR</Dept>
  </Employee>
  <Employee type="Permanent">
    <ID>104</ID>
    <FirstName>Krishna</FirstName>
    <LastName>Jha</LastName>
    <Dept>Recruitment</Dept>
  </Employee>
  <Employee type="Contract">
    <ID>105</ID>
    <FirstName>Suresh</FirstName>
    <LastName>Babu</LastName>
    <Dept>Account</Dept>
  </Employee>
</Employees>

XPath expression Syntax
Some of important expressions given below which are used to build an XPath query
Expression
Description
node
To select all child nodes under the node “node”
/
To select the root node
//
To select the node from any where in the document.
.
To select the current node
..
To select the parent of the current node
@
To select attributes

we will see how these XPath expressions can be used in .net world to access and manipulate XML contents. To show we will use XmlDocument class System.Xml namespace.  We can use SelectSingleNode() and SelectNodes() methods of XmlDocument class to query the XML using XPath expression.

To select a single node, for example first name:-
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath("~/App_Data/Employees.xml"));
Response.Write(xmldoc.SelectSingleNode("/Employees/Employee/FirstName").InnerText);
Output will be :- 
Rakesh

To select nth occurence of a node value, for example to get 3rd employee’s firstname:-
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath("~/App_Data/Employees.xml"));
Response.Write(xmldoc.SelectSingleNode("/Employees/Employee[3]/FirstName").InnerText);
OUTPUT
Richa

To select a node conditionally, for example to select firstname of a employee with ID as 101:-
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath("~/App_Data/Employees.xml"));
Response.Write(xmldoc.SelectSingleNode("/Employees/Employee[ID=101]/FirstName").InnerText);
OUTPUT
Radha

To select a attribute of a XML node, for example to get the type of employee with ID 101:-
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath("~/App_Data/Employees.xml"));
Response.Write(xmldoc.SelectSingleNode("/Employees/Employee[ID=101]/@type").InnerText)
OUTPUT
Contract

To get a count of all permanent employees:-
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath("~/App_Data/Employees.xml"));
Response.Write(xmldoc.SelectNodes("/Employees/Employee[@type='Permanent']").Count.ToString())
OUTPUT
3

To get all employee count:-
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath("~/App_Data/Employees.xml"));
Response.Write(xmldoc.SelectNodes("//Employee").Count.ToString());
OUTPUT
6
With the given below examples we will see the basic usages of XPath expressions to query the XML content and usages of XPath related classes in System.Xml.XPath namespace in .Net Framework. At times, we need to fetch some set of XML nodes to populate an ASP.Net control.
In our example we populate the dropdownlist form the given above XML file. Through code will fetch all permanent employees, contract employees, all employees and populate them to a ddlPermanentEmp, ddlContractEmp, ddlAllEmployees DropDownList respectively.

Default3.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="Permanent Employee"></asp:Label>
        <asp:DropDownList ID="ddlPermanentEmp" runat="server">
        </asp:DropDownList>
        <br />
        <asp:Label ID="Label2" runat="server" Text="Contract Employee"></asp:Label>
        <asp:DropDownList ID="ddlContractEmp" runat="server">
        </asp:DropDownList>
        <br />
        <asp:Label ID="Label3" runat="server" Text="All Employee"></asp:Label>
        <asp:DropDownList ID="ddlAllEmployees" runat="server">
        </asp:DropDownList>
        <br />
      </div>
    </form>
</body>
</html>

Default3.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Data;

public partial class Default3 : System.Web.UI.Page

{
    protected void Page_Load(object sender, EventArgs e)
    {
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(Server.MapPath("~/App_Data/sample.xml"));
        //Get permanent employees
        XmlNodeList nodes = xmldoc.SelectNodes("/Employees/Employee[@type='Permanent']");
        foreach (XmlNode node in nodes)
        {
             ddlPermanentEmp.Items.Add(newListItem(node.SelectSingleNode("FirstName").InnerText, node.SelectSingleNode("ID").InnerText));
        }
        //Get contract employees
        nodes = xmldoc.SelectNodes("/Employees/Employee[@type='Contract']");
        foreach (XmlNode node in nodes)
        {
            ddlContractEmp.Items.Add(new ListItem(node.SelectSingleNode("FirstName").InnerText, node.SelectSingleNode("ID").InnerText));
        }

        //Get all employees

        nodes = xmldoc.SelectNodes("//Employee");
        foreach (XmlNode node in nodes)
        {
            ddlAllEmployees.Items.Add(new ListItem(node.SelectSingleNode("FirstName").InnerText, node.SelectSingleNode("ID").InnerText));
        }
    }
}


Output :- 

Permanent Employee   
Contract Employee   
All Employee    


XPathNavigator in XML 


The System.Xml.XPath namespace has a class called XPathNavigator which can be used for both forward and backward navigation of XML nodes. Technically, it is an abstract class which defines a cursor model for navigating and editing XML information items as instances of the XPath 2.0 Data Model. Once after selecting the XML nodes using an XPath expression, it uses XPathNodeIterator class to iterate through the XML nodes.
To create XPathNavigator object, we need to call the CreateNavigator() method on XmlDocument or XpathDocument object. The below code will read all permanent employees and load it to a DropDownList ddlEmployees.

Default3.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label3" runat="server" Text="All Employee"></asp:Label>
        <asp:DropDownList ID="ddlAllEmployees" runat="server"></asp:DropDownList>
        <br />
    </div>
    </form>
</body>
</html>

Default3.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Data;
using System.Xml.XPath;

public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        XPathDocument xpathdoc = new XPathDocument(Server.MapPath("~/App_Data/sample.xml"));
        XPathNavigator navigator = xpathdoc.CreateNavigator();
        XPathExpression expr = navigator.Compile("/Employees/Employee[@type='Permanent']");
        XPathNodeIterator nodes = navigator.Select(expr);
        while (nodes.MoveNext())
        {
            ddlAllEmployees.Items.Add(new ListItem(nodes.Current.SelectSingleNode("FirstName").Value, nodes.Current.SelectSingleNode("ID").Value));
        }
    }
}

Output:- 

All Employee  

No comments:

Post a Comment