5,316,172 members and growing! (20,571 online)
Email Password   helpLost your password?
Languages » XML » General License: The Code Project Open License (CPOL)

Introduction to using XPathDocument, XPathNodeIterator, XPathNavigator and XPathExpression Objects

By Usman M Khan

Introduction to using XPathDocument, XPathNodeIterator, XPathNavigator and XPathExpression Objects
C# (C# 1.0, C# 2.0, C# 3.0, C#)

Posted: 9 May 2008
Updated: 9 May 2008
Views: 4,076
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
15 votes for this Article.
Popularity: 4.07 Rating: 3.46 out of 5
0 votes, 0.0%
1
2 votes, 13.3%
2
2 votes, 13.3%
3
7 votes, 46.7%
4
4 votes, 26.7%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Introduction

In this article I will try to introduce XPath Data Model and the way we can navigate through xml document, manipulate it and run expressions against it.

1- Creating XPathDocument and XPathNavigator Object
2- Selecting XML Data using XPathNodeIterator
3- Inserting XML Data
4- Evaluating XML Data using XPathExpressions

Before we proceed, lets first create a small xml file - EE.xml and place it in App_Code folder of our web solution.

<?xml version="1.0" standalone="yes"?>
<PlotsDataSet>
  <Plot>
    <PlotStatus>
      <PlotID>4</PlotID>
      <PlotStatus>In Active</PlotStatus>
    </PlotStatus>
    <PlotDescription>
      <PlotName>3 Shrewsbury Road</PlotName>
      <PlotSize>30 Sq. Yards</PlotSize>
    </PlotDescription>
    <PlotPrice>50000</PlotPrice>
  </Plot>
</PlotsDataSet>

Secondly make sure that we have added the reference to following namespace:

using System.Xml;
using System.Xml.XPath;

Thirdly, add a TextBox on form and make it multiline.

1- Creating XPathDocument and XPathNavigator Object

Simply create an instantiation of XPathDocument class and populate the object with xml data from the file that we have stored in App_Code. Then we will call the CreateNavigator method on XPathDocument object which thus gives us the XPathNavigator Object. Thats how we will do this:
        XPathDocument doc = new XPathDocument(Server.MapPath("App_Code//EE.xml"));
       
        XPathNavigator nav = doc.CreateNavigator();

2- Selecting XML Data using XPathNodeIterator

XPathNodeIterator lets us get through all the nodes, lets say I want to get PlotName node information in all Plot Elements. We can achieve this by creating XPathNodeIterator object and using its MoveNext() method.
        XPathNodeIterator xnodes = nav.Select("/PlotsDataSet/Plot/PlotDescription/PlotName");

        TextBox1.Text += "Plot Names:" + "\n";

        while (xnodes.MoveNext())
        {
            TextBox1.Text += "\n"+ xnodes.Current.InnerXml;

        }

3- Inserting XML Data

Once we have added an XML Navigator we can call any of its methods to manipulate the XML within XMLDocument. For example we have methods to insert elements, append/prepend child elements. XML Navigator object has several methods with the help of which we can navigate an XML Document and change or add information that we want to. Lets insert <Discount>Yes - 15 Percent</Discount> right after the PlotPrice Element.
        XPathNavigator nav2 = doc.CreateNavigator();

            nav2.MoveToChild("PlotsDataSet", string.Empty);
            nav2.MoveToChild("Plot", string.Empty);
            nav2.MoveToChild("PlotPrice", string.Empty);
            nav2.InsertAfter("<Discount>Yes - 15 Percent</Discount>");
            nav2.MoveToParent();
          
        TextBox1.Text += nav2.OuterXml;
            doc.Save(Server.MapPath("App_Code//EE.xml"));

If we now look at the XML document, its changed with Discount element added right after PlotPrice Element.

<?xml version="1.0" standalone="yes"?>
<PlotsDataSet>
  <Plot>
    <PlotStatus>
      <PlotID>4</PlotID>
      <PlotStatus>In Active</PlotStatus>
    </PlotStatus>
    <PlotDescription>
      <PlotName>3 Shrewsbury Road</PlotName>
      <PlotSize>30 Sq. Yards</PlotSize>
    </PlotDescription>
    <PlotPrice>50000</PlotPrice>
    <Discount>Yes - 15 Percent</Discount>
  </Plot>
</PlotsDataSet>

4- Evaluating XML Data using XPathExpression

With XPath Navigator we also have capability to evaluate expression within our xpath model. To achieve this we must have XML Document or XPath Document. Then we can create our XPath Navigator based on either one of them. Once we have xpath navigator, we can simply call its evaluate method and pass in the expression that we like to evaluate.
        XPathNavigator nav3 = doc.CreateNavigator();

        XPathExpression xpr = nav3.Compile("/PlotsDataSet/Plot/PlotPrice/text() * 0.15");
        Double DiscountedPrice = Convert.ToDouble(nav3.Evaluate(xpr));

        TextBox1.Text += "\n" + "Total Discount: "+ DiscountedPrice.ToString();

I hope you have enjoyed the article. If you come across any questions, do let me know.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Usman M Khan



Occupation: Software Developer
Company: UK based IT Contractor
Location: United Kingdom United Kingdom

Other popular XML articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 3 of 3 (Total in Forum: 3) (Refresh)FirstPrevNext
Subject  Author Date 
Generalnice articlememberJimmy Zhang12:24 10 May '08  
Generallinq?memberyassir hannoun4:19 10 May '08  
GeneralRe: linq?memberRicky Wang16:16 13 May '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 9 May 2008
Editor:
Copyright 2008 by Usman M Khan
Everything else Copyright © CodeProject, 1999-2008
Web13 | Advertise on the Code Project