Querying XML with XPathDocument and XPathNodeIterator (C#) : XPath « XML « ASP.NET Tutorial






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

<!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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>

File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Xml;
using System.Xml.XPath;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string booksFile = Path.Combine(Request.PhysicalApplicationPath, "Data.xml");

        XPathDocument document = new XPathDocument(booksFile);
        XPathNavigator nav = document.CreateNavigator();

        XmlNamespaceManager namespaceMgr = new XmlNamespaceManager(nav.NameTable);
        namespaceMgr.AddNamespace("b", "http://example.books.com");

        foreach (XPathNavigator node in nav.Select("//b:book[not(b:price[. > 10.00])]/b:price",namespaceMgr))
        {
            Decimal price = (decimal)node.ValueAs(typeof(decimal));
            Response.Write(String.Format("Price is {0}<BR/>", price));
        }
    }

}
File: Data.xml

<?xml version='1.0'?>
<bookstore xmlns="http://example.books.com"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <book genre="A" 
          publicationdate="1981" 
          ISBN="1-11111-11-0">
        <title>title 1</title>
        <author>
            <first-name>A</first-name>
            <last-name>B</last-name>
        </author>
        <price>8</price>
    </book>
    <book genre="B" 
          publicationdate="1999" 
          ISBN="0-222-22222-2">
        <title>title 2</title>
        <author>
            <first-name>C</first-name>
            <last-name>D</last-name>
        </author>
        <price>11.99</price>
    </book>
</bookstore>








25.17.XPath
25.17.1.Use XPath to navigate XML document (VB.net)
25.17.2.Use XPath to query XML data (VB.net)
25.17.3.XPath Navigator Read
25.17.4.XPath Search
25.17.5.Querying XML with XPathDocument and XPathNodeIterator (C#)
25.17.6.Querying XML with XPathDocument and XPathNodeIterator (VB)