XPath

The examples in this section all use the following XML file:

 

        <?xml version="1.0" encoding="utf-8" standalone="yes"?>
        <customers>
            <customer id="123" status="archived">
                <firstname>Jack</firstname>
                <lastname>Smith</lastname>
            </customer>
            <customer>
                <firstname>Tom</firstname>
                <lastname>James</lastname>
            </customer>
        </customers>

  

The SelectXXX methods accept an XPath query string.

For example, the following finds the firstname node of an XmlDocument:


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Text;
using System.IO;
class Program
{
    static void Main()
    {
        XmlDocument doc = new XmlDocument();
        doc.Load("customers.xml");
        XmlNode n = doc.SelectSingleNode("customers/customer[firstname='Jack']");
        Console.WriteLine(n.InnerText);  
    }
}

The output:


JackSmith

Common XPath operators

OperatorDescription
/Children
//Recursively children
.Current node (usually implied)
..Parent node
*Wildcard
@Attribute
[]Filter
:Namespace separator
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.