CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Using XPath Expression to Access or Read XML document in ASP.Net

By Bala Murugan
Posted On Jun 15,2010
Article Rating:
Be first to rate
this article.
No of Comments: 0
Category: ASP.Net
Print this article.

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

 

XML is one of the widely used data exchange format for variety of reasons in software industry. Hence, working on XML data like selecting a XML node, navigating the XML node tree for finding a node or doing some manipulation on XML nodes has become one of the major and repetitive tasks in any project we work. In this article, we will try to understand how to read XML data using XPath expression in ASP.Net.

 

What is XPath expression?

Understanding the increasing need of XML, 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 simple XML.

<?xml version="1.0" encoding="utf-8"?>

<Employees>

  <Employee type="Permanent">

    <ID>100</ID>

    <FirstName>Bala</FirstName>

    <LastName>Murugan</LastName>

    <Dept>Production Support</Dept>

  </Employee>

  <Employee type="Contract">

    <ID>101</ID>

    <FirstName>Peter</FirstName>

    <LastName>Laurence</LastName>

    <Dept>Development</Dept>

  </Employee>

  <Employee type="Permanent">

    <ID>102</ID>

    <FirstName>Rick</FirstName>

    <LastName>Anderson</LastName>

    <Dept>Sales</Dept>

  </Employee>

  <Employee type="Contract">

    <ID>103</ID>

    <FirstName>Ramesh</FirstName>

    <LastName>Kumar</LastName>

    <Dept>HR</Dept>

  </Employee>

  <Employee type="Permanent">

    <ID>104</ID>

    <FirstName>Katie</FirstName>

    <LastName>Yu</LastName>

    <Dept>Recruitment</Dept>

  </Employee>

  <Employee type="Contract">

    <ID>105</ID>

    <FirstName>Suresh</FirstName>

    <LastName>Babu</LastName>

    <Dept>Inventory</Dept>

  </Employee>

</Employees>

 

XPath expression Syntax

The XPath expression will use / to select the root node of the XML document. For example, to select all the employee nodes in the above XML we have to use the below XPath query,

/Employees/Employee

 

The above XPath query will return all nodes under every <Employee> nodes. 

 

The below table list some of the important expressions 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

 

Moving forward, we will see how these XPath expressions can be used in .net world to access and manipulate XML contents.

 

In this section, we will see how to read a XML node at a very basic level using XmlDocument class System.Xml namespace.  We can use SelectSingleNode() and SelectNodes() methods of XmlDocument class to query the XML using XPath expression. See below,

 

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

Bala

 

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

Rick

 

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

Peter

 

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

 




At times, we need to fetch some set of XML nodes to populate an ASP.Net control. The below code will fetch all permanent employees, contract employees, all employees and populate them to a ddlPermanentEmp, ddlContractEmp, ddlAllEmployees DropDownList respectively.

 

XmlDocument xmldoc = new XmlDocument();

xmldoc.Load(Server.MapPath("~/App_Data/Employees.xml"));

//Get permanent employees

  XmlNodeList nodes = xmldoc.SelectNodes("/Employees/Employee[@type='Permanent']");

        foreach (XmlNode node in nodes)

        {          

            ddlPermanentEmp.Items.Add(new ListItem(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));

        }

 

Thus, with the above examples we have seen some of basic usages of XPath expressions to query the XML content.

In the coming section, we will see the usages of XPath related classes in System.Xml.XPath namespace in .NetFramework.

 

XPath support in .NetFramework

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.

        XPathDocument xpathdoc = new XPathDocument(Server.MapPath("~/App_Data/Employees.xml"));

        XPathNavigator navigator = xpathdoc.CreateNavigator();

        XPathExpression expr = navigator.Compile("/Employees/Employee[@type='Permanent']");

        XPathNodeIterator nodes = navigator.Select(expr);

 

        while (nodes.MoveNext())

        {

            ddlEmployees.Items.Add(new ListItem(nodes.Current.SelectSingleNode("FirstName").Value, nodes.Current.SelectSingleNode("ID").Value));

        }

 

Reference

http://www.w3schools.com/xpath/default.asp

 

Downloads

Download Source 

Conclusion

Thus, we have seen how to query an xml document to fetch a XML data using XPath expression. You can read the link posted in the reference section to know more about building XPath query. We will see more about editing, inserting and deleting the XML data using the classes available in .Netframework in future articles.

Download the source attached with this article and see the above examples in action.

 

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments