System.Xml.XPath.XPathNavigator Class

Assembly: System.Xml.dll
Namespace: System.Xml.XPath
Summary
Reads data from any data store using a cursor model.
C# Syntax:
public abstract class XPathNavigator : ICloneable
Remarks
XPathNavigator is based on the XPath data model and provides the methods required to implement XPath queries over any data store. To create an XPathNavigator over an XML document or a DataSet (using the XmlDataDocument class), use the CreateNavigator method available in the XmlNode and XPathDocument classes, which implement the IXPathNavigable interface. Additionally, you can create your own implementation of XPathNavigator over other data stores such as file systems or databases. For more information on implementing your own XPathNavigator, see the conceptual topic at MSDN: xpathnavigatoroverdifferentstores.

XPathNavigator provides read-only, random access to data. The current node refers to the node on which the navigator is positioned. The navigator is advanced using any of the move methods and properties reflect the value of the current node. If the navigator is created by XmlDocument, you can use the IHasXmlNode.GetNode method to return the XmlNode representing the current position of the navigator.

XPathNavigator supports XSLT and can be used as an input mechanism to the XslTransform.Transform method.

For more information on the XPath data model, see the W3C XML Path Language (XPath) recommendation located at http://www.w3.org/TR/xpath.

See also:
System.Xml.XPath Namespace | XslTransform | IHasXmlNode

System.Xml.XPath.XPathNavigator Member List:

Public Properties
BaseURI Read-only

Gets the base URI for the current node.
HasAttributes Read-only

Gets a value indicating whether the element node has any attributes.
HasChildren Read-only

Gets a value indicating whether the current node has child nodes.
IsEmptyElement Read-only

Gets a value indicating whether the current node is an empty element (for example, <MyElement/>).
LocalName Read-only

Gets the name of the current node without the namespace prefix.
Name Read-only

Gets the qualified name of the current node.
NamespaceURI Read-only

Gets the namespace URI (as defined in the W3C Namespace Specification) of the current node.
NameTable Read-only

Gets the XmlNameTable associated with this implementation.
NodeType Read-only

Gets the type of the current node.
Prefix Read-only

Gets the prefix associated with the current node.
Value Read-only

Gets the text value of the current node.
XmlLang Read-only

Gets the xml:lang scope for the current node.
Public Methods
Clone Creates a new XPathNavigator positioned at the same node as this XPathNavigator.
ComparePosition Compares the position of the current navigator with the position of the specified XPathNavigator.
Compile Compiles a string representing an XPath expression and returns an XPathExpression.
Equals
(inherited from System.Object)
See base class member description: System.Object.Equals

Derived from System.Object, the primary base class for all objects.
Evaluate Overloaded:
Evaluate(string xpath)

Evaluates the string representing an XPath expression and returns the typed result (number, Boolean, string, or node set). Use the XPathNodeIterator to iterate over a set of nodes.
Evaluate Overloaded:
Evaluate(XPathExpression expr)

Evaluates the XPathExpression and returns the typed result (number, Boolean, string, or node set). Use the XPathNodeIterator to iterate over a set of nodes.
Evaluate Overloaded:
Evaluate(XPathExpression expr, XPathNodeIterator context)

Evaluates the XPathExpression using the supplied context and returns the typed result (number, Boolean, string, or node set).
GetAttribute Gets the value of the attribute with the specified XPathNavigator.LocalName and XPathNavigator.NamespaceURI.
GetHashCode
(inherited from System.Object)
See base class member description: System.Object.GetHashCode

Derived from System.Object, the primary base class for all objects.
GetNamespace Returns the value of the namespace node corresponding to the specified local name.
GetType
(inherited from System.Object)
See base class member description: System.Object.GetType

Derived from System.Object, the primary base class for all objects.
IsDescendant Determines whether the specified XPathNavigator is a descendant of the current XPathNavigator.
IsSamePosition Determines whether the current XPathNavigator is at the same position as the specified XPathNavigator.
Matches Overloaded:
Matches(string xpath)

Determines whether the current node matches the specified XSLT pattern.
Matches Overloaded:
Matches(XPathExpression expr)

Determines whether the current node matches the specified XPathExpression.
MoveTo Moves to the same position as the specified XPathNavigator.
MoveToAttribute Moves to the attribute with matching XPathNavigator.LocalName and XPathNavigator.NamespaceURI.
MoveToFirst Moves to the first sibling of the current node.
MoveToFirstAttribute Moves to the first attribute.
MoveToFirstChild Moves to the first child of the current node.
MoveToFirstNamespace Overloaded:
MoveToFirstNamespace()

Moves the XPathNavigator to first namespace node of the current element.
MoveToFirstNamespace Overloaded:
MoveToFirstNamespace(XPathNamespaceScope namespaceScope)

Moves the XPathNavigator to the first namespace node matching the XPathNamespaceScope specified.
MoveToId Moves to the node that has an attribute of type ID whose value matches the specified string.
MoveToNamespace Moves the XPathNavigator to the namespace node with the specified local name.
MoveToNext Moves to the next sibling of the current node.
MoveToNextAttribute Moves to the next attribute.
MoveToNextNamespace Overloaded:
MoveToNextNamespace()

Moves the XPathNavigator to the next namespace node.
MoveToNextNamespace Overloaded:
MoveToNextNamespace(XPathNamespaceScope namespaceScope)

Moves the XPathNavigator to the next namespace node matching the XPathNamespaceScope specified.
MoveToParent Moves to the parent of the current node.
MoveToPrevious Moves to the previous sibling of the current node.
MoveToRoot Moves to the root node to which the current node belongs.
Select Overloaded:
Select(string xpath)

Selects a node set using the specified XPath expression.
Select Overloaded:
Select(XPathExpression expr)

Selects a node set using the specified XPathExpression.
SelectAncestors Overloaded:
SelectAncestors(XPathNodeType type, bool matchSelf)

Selects all the ancestor element nodes of the current node with the matching XPathNodeType.
SelectAncestors Overloaded:
SelectAncestors(string name, string namespaceURI, bool matchSelf)

Selects all the ancestor element nodes of the current node with the supplied local name and namespace URI.
SelectChildren Overloaded:
SelectChildren(XPathNodeType type)

Selects all the child nodes of the current node with the matching XPathNodeType.
SelectChildren Overloaded:
SelectChildren(string name, string namespaceURI)

Selects all the child element nodes of the current node with the supplied local name and namespace URI.
SelectDescendants Overloaded:
SelectDescendants(XPathNodeType type, bool matchSelf)

Selects all the descendant nodes of the current node with the matching XPathNodeType.
SelectDescendants Overloaded:
SelectDescendants(string name, string namespaceURI, bool matchSelf)

Selects all the descendant element nodes of the current node with the supplied local name and namespace URI.
ToString Overridden:
Gets the text value of the current node. This method is equivalent to returning the XPathNavigator.Value property.
Protected Constructors
ctor #1 Default constructor. This constructor is called by derived class constructors to initialize state in this type.
Protected Methods
Finalize
(inherited from System.Object)
See base class member description: System.Object.Finalize

Derived from System.Object, the primary base class for all objects.
MemberwiseClone
(inherited from System.Object)
See base class member description: System.Object.MemberwiseClone

Derived from System.Object, the primary base class for all objects.

Hierarchy:


System.Xml.XPath.XPathNavigator Member Details

ctor #1
Summary:
Default constructor. This constructor is called by derived class constructors to initialize state in this type.
C# Syntax:
protected XPathNavigator();

Return to top


Property: BaseURI (read-only)
Summary
Gets the base URI for the current node.
C# Syntax:
public abstract string BaseURI {get;}
Remarks
A networked XML document is comprised of chunks of data, aggregated using various W3C standard inclusion mechanisms, and therefore contains nodes that come from different places. DTD entities are an example of this, however, this is not limited to DTDs. The BaseURI property tells you where these nodes originate from.

For example, if the XML data is loaded from http://server/mydata.xml then BaseURI returns http://server/mydata.xml.

Return to top


Property: HasAttributes (read-only)
Summary
Gets a value indicating whether the element node has any attributes.
C# Syntax:
public abstract bool HasAttributes {get;}
See also:
XPathNavigator.MoveToNextAttribute | XPathNavigator.MoveToFirstAttribute | XPathNavigator.MoveToAttribute | XPathNavigator.GetAttribute

Return to top


Property: HasChildren (read-only)
Summary
Gets a value indicating whether the current node has child nodes.
C# Syntax:
public abstract bool HasChildren {get;}
Remarks
The following table lists the XPathNodeType and what type of child nodes they may have, if any.

XPathNodeType Child Nodes
Root Element, comment or processing instruction nodes.
Element Element, text, comment, whites pace or significant white space nodes.
All other XpathNodeType nodes These node types cannot have child nodes.
See also:
XPathNavigator.MoveToFirstChild | XPathNavigator.MoveToParent | XPathNavigator.MoveToNext

Return to top


Property: IsEmptyElement (read-only)
Summary
Gets a value indicating whether the current node is an empty element (for example, <MyElement/>).
C# Syntax:
public abstract bool IsEmptyElement {get;}
Remarks
This property enables you to determine the difference between the following:

<item bar="123"/> (IsEmptyElement is true).

<item bar="123"></item> (IsEmptyElement is false).

<item bar="123">test</item> (IsEmptyElement is false).

Return to top


Property: LocalName (read-only)
Summary
Gets the name of the current node without the namespace prefix.
C# Syntax:
public abstract string LocalName {get;}
Example
The following example walks the node tree recursively and displays information on element and text nodes.
public static void RecursiveWalk(XPathNavigator nav)
{
   switch (nav.NodeType){
     case XPathNodeType.Element:
        if (nav.Prefix==String.Empty)
          Console.WriteLine("<{0}>", nav.LocalName);
        else
          Console.Write("<{0}:{1}>", nav.Prefix, nav.LocalName);
          Console.WriteLine("\t"+ nav.NamespaceURI);
        break;
     case XPathNodeType.Text:
        Console.WriteLine("\t" + nav.Value);
        break;
    }

    if ( nav.MoveToFirstChild() )
   {
      do{
         RecursiveWalk(nav);
      } while ( nav.MoveToNext() );

      nav.MoveToParent();
      if (nav.NodeType == XPathNodeType.Element)
        Console.WriteLine("</{0}>", nav.Name);
    }
}	

    
See also:
XPathNavigator.Name | XPathNavigator.Prefix

Return to top


Property: Name (read-only)
Summary
Gets the qualified name of the current node.
C# Syntax:
public abstract string Name {get;}
Example
The following example walks the node tree recursively and displays information on element and text nodes.
public static void RecursiveWalk(XPathNavigator nav)
{
   switch (nav.NodeType){
     case XPathNodeType.Element:
        if (nav.Prefix==String.Empty)
          Console.WriteLine("<{0}>", nav.LocalName);
        else
          Console.Write("<{0}:{1}>", nav.Prefix, nav.LocalName);
          Console.WriteLine("\t"+ nav.NamespaceURI);
        break;
     case XPathNodeType.Text:
        Console.WriteLine("\t" + nav.Value);
        break;
    }

    if ( nav.MoveToFirstChild() )
   {
      do{
         RecursiveWalk(nav);
      } while ( nav.MoveToNext() );

      nav.MoveToParent();
      if (nav.NodeType == XPathNodeType.Element)
        Console.WriteLine("</{0}>", nav.Name);
    }
}	

    
See also:
XPathNavigator.LocalName | XPathNavigator.Prefix

Return to top


Property: NamespaceURI (read-only)
Summary
Gets the namespace URI (as defined in the W3C Namespace Specification) of the current node.
C# Syntax:
public abstract string NamespaceURI {get;}
Remarks
Only element and attribute nodes can have a namespace URI.
Example
The following example walks the node tree recursively and displays information on element and text nodes.
public static void RecursiveWalk(XPathNavigator nav)
{
   switch (nav.NodeType){
     case XPathNodeType.Element:
        if (nav.Prefix==String.Empty)
          Console.WriteLine("<{0}>", nav.LocalName);
        else
          Console.Write("<{0}:{1}>", nav.Prefix, nav.LocalName);
          Console.WriteLine("\t"+ nav.NamespaceURI);
        break;
     case XPathNodeType.Text:
        Console.WriteLine("\t" + nav.Value);
        break;
    }

    if ( nav.MoveToFirstChild() )
   {
      do{
         RecursiveWalk(nav);
      } while ( nav.MoveToNext() );

      nav.MoveToParent();
      if (nav.NodeType == XPathNodeType.Element)
        Console.WriteLine("</{0}>", nav.Name);
    }
}	

    
See also:
XPathNodeType | XPathNavigator.Prefix

Return to top


Property: NameTable (read-only)
Summary
Gets the XmlNameTable associated with this implementation.
C# Syntax:
public abstract XmlNameTable NameTable {get;}
Remarks
The XmlNameTable stores atomized strings of any XPathNavigator.LocalName, XPathNavigator.NamespaceURI, and XPathNavigator.Prefix used by XPathNavigator. This means that when the same name is returned multiple times (like "book") then the same String object is returned for that name. This makes it possible to write efficient code that does object comparisons on these strings instead of expensive string comparisons.

For more information on atomized strings, see XmlNameTable.

Return to top


Property: NodeType (read-only)
Summary
Gets the type of the current node.
C# Syntax:
public abstract XPathNodeType NodeType {get;}
Example
The following example walks the node tree recursively and displays information on element and text nodes.
public static void RecursiveWalk(XPathNavigator nav)
{
   switch (nav.NodeType){
     case XPathNodeType.Element:
        if (nav.Prefix==String.Empty)
          Console.WriteLine("<{0}>", nav.LocalName);
        else
          Console.Write("<{0}:{1}>", nav.Prefix, nav.LocalName);
          Console.WriteLine("\t"+ nav.NamespaceURI);
        break;
     case XPathNodeType.Text:
        Console.WriteLine("\t" + nav.Value);
        break;
    }

    if ( nav.MoveToFirstChild() )
   {
      do{
         RecursiveWalk(nav);
      } while ( nav.MoveToNext() );

      nav.MoveToParent();
      if (nav.NodeType == XPathNodeType.Element)
        Console.WriteLine("</{0}>", nav.Name);
    }
}	

    

Return to top


Property: Prefix (read-only)
Summary
Gets the prefix associated with the current node.
C# Syntax:
public abstract string Prefix {get;}
Example
The following example walks the node tree recursively and displays information on element and text nodes.
public static void RecursiveWalk(XPathNavigator nav)
{
   switch (nav.NodeType){
     case XPathNodeType.Element:
        if (nav.Prefix==String.Empty)
          Console.WriteLine("<{0}>", nav.LocalName);
        else
          Console.Write("<{0}:{1}>", nav.Prefix, nav.LocalName);
          Console.WriteLine("\t"+ nav.NamespaceURI);
        break;
     case XPathNodeType.Text:
        Console.WriteLine("\t" + nav.Value);
        break;
    }

    if ( nav.MoveToFirstChild() )
   {
      do{
         RecursiveWalk(nav);
      } while ( nav.MoveToNext() );

      nav.MoveToParent();
      if (nav.NodeType == XPathNodeType.Element)
        Console.WriteLine("</{0}>", nav.Name);
    }
}	

    

Return to top


Property: Value (read-only)
Summary
Gets the text value of the current node.
C# Syntax:
public abstract string Value {get;}
Example
The following example walks the node tree recursively and displays information on element and text nodes.
public static void RecursiveWalk(XPathNavigator nav)
{
   switch (nav.NodeType){
     case XPathNodeType.Element:
        if (nav.Prefix==String.Empty)
          Console.WriteLine("<{0}>", nav.LocalName);
        else
          Console.Write("<{0}:{1}>", nav.Prefix, nav.LocalName);
          Console.WriteLine("\t"+ nav.NamespaceURI);
        break;
     case XPathNodeType.Text:
        Console.WriteLine("\t" + nav.Value);
        break;
    }

    if ( nav.MoveToFirstChild() )
   {
      do{
         RecursiveWalk(nav);
      } while ( nav.MoveToNext() );

      nav.MoveToParent();
      if (nav.NodeType == XPathNodeType.Element)
        Console.WriteLine("</{0}>", nav.Name);
    }
}	

    

Return to top


Property: XmlLang (read-only)
Summary
Gets the xml:lang scope for the current node.
C# Syntax:
public abstract string XmlLang {get;}
Remarks
Using the XML text below, if the navigator were positioned on the name element, the user can call this property to find out that the element is in the scope of a US English xml:lang attribute.
              <root xml:lang="en-us">
               <name>Fred</name>
              </root>
                 
            

Return to top


Method: Clone()
Summary
Creates a new XPathNavigator positioned at the same node as this XPathNavigator.
C# Syntax:
public abstract XPathNavigator Clone();
Return Value:
A new XPathNavigator object positioned at the same node as the original XPathNavigator.
Remarks
This method is especially useful when used in conjunction with XPathNodeIterator.XPathNodeIterator is used to iterate over a selected node set and contains a XPathNodeIterator.Current property which returns an XPathNavigator positioned on the context node of the XPathNodeIterator. However, the XPathNavigator returned by the Current property cannot be used to move away from the node set. Instead, you should clone the returned XPathNavigator and use the cloned navigator to do any additional moves.

The cloned XPathNavigator is not affected by subsequent changes to the original XPathNavigator.

Example
The following example gets all book titles authored by Jane Austen.
using System;
using System.Xml.XPath;

public class Sample
{
  public static void Main()
  {

    XPathDocument doc = new XPathDocument("booksort.xml");
    XPathNavigator nav = doc.CreateNavigator();

    // Select all books authored by Austen.
    XPathNodeIterator ni = nav.Select("descendant::book[author/last-name='Austen']");
    while (ni.MoveNext()){
       // Clone the navigator returned by the Current property. 
       // Use the cloned the navigator to get the title element.
       XPathNavigator clone = ni.Current.Clone();
       clone.MoveToFirstChild();
       Console.WriteLine("Book title: {0}", clone.Value);
    }
  }
}

    

The example uses the booksort.xml file as input.

<?xml version="1.0"?>
<!-- a fragment of a book store inventory database -->
<bookstore xmlns:bk="urn:samples">
  <book genre="novel" publicationdate="1997" bk:ISBN="1-861001-57-8">
    <title>Pride And Prejudice</title>
    <author>
      <first-name>Jane</first-name>
      <last-name>Austen</last-name>
    </author>
    <price>24.95</price>
  </book>
  <book genre="novel" publicationdate="1992" bk:ISBN="1-861002-30-1">
    <title>The Handmaid's Tale</title>
    <author>
      <first-name>Margaret</first-name>
      <last-name>Atwood</last-name>
    </author>
    <price>29.95</price>
  </book>
  <book genre="novel" publicationdate="1991" bk:ISBN="1-861001-57-6">
    <title>Emma</title>
    <author>
      <first-name>Jane</first-name>
      <last-name>Austen</last-name>
    </author>
    <price>19.95</price>
  </book>
  <book genre="novel" publicationdate="1982" bk:ISBN="1-861001-45-3">
    <title>Sense and Sensibility</title>
    <author>
      <first-name>Jane</first-name>
      <last-name>Austen</last-name>
    </author>
    <price>19.95</price>
  </book>
</bookstore>

    

Return to top


Method: ComparePosition(
   XPathNavigator nav
)
Summary
Compares the position of the current navigator with the position of the specified XPathNavigator.
C# Syntax:
public virtual XmlNodeOrder ComparePosition(
   XPathNavigator nav
);
Parameters:

nav

The XPathNavigator to compare against.

Return Value:
An XmlNodeOrder value representing the comparative position of the two navigators. The following table describes the XmlNodeOrder enumeration.

XmlNodeOrder Description
Before The current node of this navigator is before the current node of the supplied navigator.
After The current node of this navigator is after the current node of the supplied navigator.
Same The two navigators are positioned on the same node.
Unknown The node positions cannot be determined in document order, relative to each other. This could occur if the two nodes reside in different trees.
Exceptions
Exception Type Condition
Exception The nav parameter is null.
Remarks
The method behavior is dependent on the node type the XPathNavigator is currently positioned on. When comparing nodes in the XML document, the following rules apply:

Note For more information on the XPath data model and details on each of the node types, see section 5 of the W3C XML Path Language (XPath) recommendation located at http://www.w3.org/TR/xpath#data-model.

This method has no effect on the state of the XPathNavigator.

See also:
XPathNavigator.IsSamePosition

Return to top


Method: Compile(
   string xpath
)
Summary
Compiles a string representing an XPath expression and returns an XPathExpression.
C# Syntax:
public virtual XPathExpression Compile(
   string xpath
);
Parameters:

xpath

A string representing an XPath expression.

Return Value:
An XPathExpression object representing the XPath expression.
Exceptions
Exception Type Condition
ArgumentException The xpath parameter contains an invalid XPath expression.
Remarks
An XPath expression is evaluated to yield one of the following return types:

Expressions that return a node set can be used in the XPathNavigator.Select and XPathNavigator.Evaluate methods. Expressions that return a boolean, number, or string can be used in the XPathNavigator.Evaluate method. The rules on valid expressions for the XPathNavigator.Matches method are specific to that method.

Example
The following example displays all ISBN attribute nodes.
using System;
using System.IO;
using System.Xml;
using System.Xml.XPath;

public class Sample
{
  public static void Main()
  {

      XPathDocument doc = new XPathDocument("booksort.xml");
      XPathNavigator nav = doc.CreateNavigator();

      //Select all ISBN attributes.
      XPathExpression expr; 
      expr = nav.Compile("/bookstore/book/@bk:ISBN");
 
      XmlNamespaceManager nsmgr = new XmlNamespaceManager(nav.NameTable);
      nsmgr.AddNamespace("bk", "urn:samples");
      expr.SetContext(nsmgr);

      //Display the selection.
      XPathNodeIterator iterator = nav.Select(expr);
      while (iterator.MoveNext()){
        Console.WriteLine(iterator.Current.ToString());
      }
   }

}

    
The example uses the file, booksort.xml, as input.

<?xml version="1.0"?>
<!-- a fragment of a book store inventory database -->
<bookstore xmlns:bk="urn:samples">
  <book genre="novel" publicationdate="1997" bk:ISBN="1-861001-57-8">
    <title>Pride And Prejudice</title>
    <author>
      <first-name>Jane</first-name>
      <last-name>Austen</last-name>
    </author>
    <price>24.95</price>
  </book>
  <book genre="novel" publicationdate="1992" bk:ISBN="1-861002-30-1">
    <title>The Handmaid's Tale</title>
    <author>
      <first-name>Margaret</first-name>
      <last-name>Atwood</last-name>
    </author>
    <price>29.95</price>
  </book>
  <book genre="novel" publicationdate="1991" bk:ISBN="1-861001-57-6">
    <title>Emma</title>
    <author>
      <first-name>Jane</first-name>
      <last-name>Austen</last-name>
    </author>
    <price>19.95</price>
  </book>
  <book genre="novel" publicationdate="1982" bk:ISBN="1-861001-45-3">
    <title>Sense and Sensibility</title>
    <author>
      <first-name>Jane</first-name>
      <last-name>Austen</last-name>
    </author>
    <price>19.95</price>
  </book>
</bookstore>

    

Return to top


Method: Equals(
   object obj
)
Inherited
See base class member description: System.Object.Equals
C# Syntax:
public virtual bool Equals(
   object obj
);

For more information on members inherited from System.Object click on the link above.

Return to top


Overloaded Method: Evaluate(
   string xpath
)
Summary
Evaluates the string representing an XPath expression and returns the typed result (number, Boolean, string, or node set). Use the XPathNodeIterator to iterate over a set of nodes.
C# Syntax:
public virtual object Evaluate(
   string xpath
);
Parameters:

xpath

A string representing an XPath expression that can be evaluated.

Return Value:
The result of the expression.
Exceptions
Exception Type Condition
ArgumentException The XPath expression contains an error.
Remarks
The following C# code converts the Price/text() node to a number, multiplies it by 10, and returns the resulting value.
              nav.Evaluate("Price/text()*10");
                 
            

Note: The XPath position() and last() functions, unless used as a predicate in a location step, require a reference to a node set in order to be evaluated. In this case, you must use the overload which takes an XPathNodeIterator as an argument; otherwise, position() and last() return 0.

This method has no effect on the state of the XPathNavigator.

Example
The following example evaluates two XPath expressions.
 XPathDocument doc = new XPathDocument("books.xml");
 XPathNavigator nav = doc.CreateNavigator();

 // Evaluate an expression that returns a number.
 string expr1 = "sum(descendant::book/price)";
 Console.WriteLine("Total price for all books: {0}", nav.Evaluate(expr1));

 // Evaluate an expression that returns a node set.
 Console.WriteLine("List each book price.");
 string expr2 = "bookstore/book/price"; 
 XPathNodeIterator ni = (XPathNodeIterator) nav.Evaluate(expr2);
 while (ni.MoveNext()){
    Console.WriteLine(ni.Current.ToString());
 }

    
See also:
XPathNavigator.Compile | XPathExpression | XPathExpression.ReturnType

Return to top


Overloaded Method: Evaluate(
   XPathExpression expr
)
Summary
Evaluates the XPathExpression and returns the typed result (number, Boolean, string, or node set). Use the XPathNodeIterator to iterate over a set of nodes.
C# Syntax:
public virtual object Evaluate(
   XPathExpression expr
);
Parameters:

expr

An XPathExpression that can be evaluated.

Return Value:
The result of the expression.
Exceptions
Exception Type Condition
ArgumentException The XPathExpression contains an error.
Remarks
The following C# code returns a number after converting the Price/text() node to a number and multiplying the value by 10.
              XPathExpression expr = nav.Compile("Price/text()*10");
              nav.Evaluate(expr);
                 
            


Note The XPath position() and last() functions, unless used as a predicate in a location step, require a reference to a node set in order to be evaluated. In this case, you must use the overload which takes an XPathNodeIterator as an argument; otherwise, position() and last() return 0.

This method has no effect on the state of the XPathNavigator.

Example
The following example calculates the total price of a customer order.
using System;
using System.IO;
using System.Xml;
using System.Xml.XPath;

public class Sample
{
  public static void Main()
  {

    XmlDocument doc = new XmlDocument();
    doc.Load("order.xml");
    XPathNavigator nav = doc.CreateNavigator();

    // Calculate the total of the order.
    XPathExpression expr = nav.Compile("sum(//price/text())");
    double total = (double) nav.Evaluate(expr);

    // If the total is more than 30 dollars, give the
    // user a 5 dollar discount.
    if (total > 30.00){
      double disc = 5.00;
      total = total - disc;
      Console.WriteLine("Total price: ${0}", total);
    }
    else
      Console.WriteLine("Total price: ${0}", total);
    
  }
}

    
The example uses the file, order.xml, as input.
<!--Represents a customer order-->
<order>
  <book ISBN='10-861003-324'>
    <title>The Handmaid's Tale</title>
    <price>19.95</price>
  </book>
  <cd ISBN='2-3631-4'>
    <title>Americana</title>
    <price>16.95</price>
  </cd>
</order>

    
See also:
XPathNavigator.Compile | XPathExpression.ReturnType

Return to top


Overloaded Method: Evaluate(
   XPathExpression expr,
   XPathNodeIterator context
)
Summary
Evaluates the XPathExpression using the supplied context and returns the typed result (number, Boolean, string, or node set).
C# Syntax:
public virtual object Evaluate(
   XPathExpression expr,
   XPathNodeIterator context
);
Parameters:

expr

An XPathExpression that can be evaluated.

context

An XPathNodeIterator pointing to the selected node set that the evaluation is to be performed on.

Return Value:
The result of the expression.
Exceptions
Exception Type Condition
ArgumentException The XPathExpression contains an error.
Remarks
The expression is evaluated using the XPathNodeIterator.Current node of the XPathNodeIterator as the context node. If context is null, the node on which the XPathNavigator is currenly positioned is used as the context node.

The position() and last() functions, unless used as a predicate in a location step, always return 0 under the following conditions:

Because the position() and last() functions work on the current node, you should not use the XPathNodeIterator.Current property to move away from the selected node set. This could invalidate the state of the XPathNavigator.

This method has no effect on the state of the XPathNavigator.

Return to top


Method: Finalize()
Inherited
See base class member description: System.Object.Finalize
C# Syntax:
~XPathNavigator();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetAttribute(
   string localName,
   string namespaceURI
)
Summary
Gets the value of the attribute with the specified XPathNavigator.LocalName and XPathNavigator.NamespaceURI.
C# Syntax:
public abstract string GetAttribute(
   string localName,
   string namespaceURI
);
Parameters:

localName

The local name of the attribute.

namespaceURI

The namespace URI of the attribute.

Return Value:
The value of the specified attribute; String.Empty if a matching attribute is not found or if the navigator is not positioned on an element node.
See also:
XPathNavigator.MoveToAttribute | XPathNavigator.MoveToFirstAttribute | XPathNavigator.MoveToNextAttribute | XPathNavigator.HasAttributes

Return to top


Method: GetHashCode()
Inherited
See base class member description: System.Object.GetHashCode
C# Syntax:
public virtual int GetHashCode();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetNamespace(
   string name
)
Summary
Returns the value of the namespace node corresponding to the specified local name.
C# Syntax:
public abstract string GetNamespace(
   string name
);
Parameters:

name

The local name of the namespace node.

Return Value:
The value of the namespace node; String.Empty if a matching namespace node is not found or if the navigator is not positioned on an element node.
Remarks
For a definition of namespace nodes, see section 5.4 of the W3C XML Path Language (XPath) recommendation located at http://www.w3.org/TR/xpath#data-model .
See also:
XPathNavigator.MoveToNamespace | XPathNavigator.MoveToFirstNamespace | XPathNavigator.MoveToNextNamespace

Return to top


Method: GetType()
Inherited
See base class member description: System.Object.GetType
C# Syntax:
public Type GetType();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: IsDescendant(
   XPathNavigator nav
)
Summary
Determines whether the specified XPathNavigator is a descendant of the current XPathNavigator.
C# Syntax:
public virtual bool IsDescendant(
   XPathNavigator nav
);
Parameters:

nav

The XPathNavigator that you want to compare against.

Return Value:
true if nav is a descendant of the current navigator; otherwise false.
Remarks
A navigator is a descendant of another navigator if it is positioned on a descendant node of the current navigator. For example, using the following XML string: <item><name>widget</name></item>

If the current navigator is positioned on the item node and nav is positioned on the name node, IsDescendant returns true.

This method always returns false under the following conditions:

Return to top


Method: IsSamePosition(
   XPathNavigator other
)
Summary
Determines whether the current XPathNavigator is at the same position as the specified XPathNavigator.
C# Syntax:
public abstract bool IsSamePosition(
   XPathNavigator other
);
Parameters:

other

The XPathNavigator that you want to compare against.

Return Value:
true if the two navigators have the same position; otherwise, false.
Remarks
This method assumes that other is an XPathNavigator that shares the same implementation and is pointing at the same document instance as the current navigator.

This method always returns false under the following conditions:

See also:
XPathNavigator.ComparePosition

Return to top


Overloaded Method: Matches(
   string xpath
)
Summary
Determines whether the current node matches the specified XSLT pattern.
C# Syntax:
public virtual bool Matches(
   string xpath
);
Parameters:

xpath

A string representing an XSLT pattern.

Return Value:
true if the current node matches the XSLT pattern; otherwise, false.
Exceptions
Exception Type Condition
ArgumentException The xpath cannot be evaluated.
Remarks
This method has no effect on the state of the XPathNavigator.

Return to top


Overloaded Method: Matches(
   XPathExpression expr
)
Summary
Determines whether the current node matches the specified XPathExpression.
C# Syntax:
public virtual bool Matches(
   XPathExpression expr
);
Parameters:

expr

An XPathExpression encapsulating a compiled XSLT pattern.

Return Value:
true if the current node matches the XPathExpression; otherwise, false.
Exceptions
Exception Type Condition
ArgumentException The expr cannot be evaluated.
Remarks
This method has no effect on the state of the XPathNavigator.
Example
The following example displays the titles of all novels.
using System;
using System.Xml.XPath;

public class Sample
{
  public static void Main()
  {

    XPathDocument doc = new XPathDocument("books.xml");
    XPathNavigator nav = doc.CreateNavigator();
 
    // Select all book nodes.
    XPathNodeIterator ni = nav.SelectDescendants("book", "", false);

    // Select all book nodes that have the matching attribute value.
    XPathExpression expr = nav.Compile("book[@genre='novel']");
    while (ni.MoveNext()) {
       XPathNavigator nav2 = ni.Current.Clone();
       if (nav2.Matches(expr)){
         nav2.MoveToFirstChild();
         Console.WriteLine("Book title:  {0}", nav2.Value);
       }
    }
  }
}

    
The example uses the file, books.xml, as input.
<bookstore>
  <book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0">
    <title>The Autobiography of Benjamin Franklin</title>
    <author>
      <first-name>Benjamin</first-name>
      <last-name>Franklin</last-name>
    </author>
    <price>8.99</price>
  </book>
  <book genre="novel" publicationdate="1967" ISBN="0-201-63361-2">
    <title>The Confidence Man</title>
    <author>
      <first-name>Herman</first-name>
      <last-name>Melville</last-name>
    </author>
    <price>11.99</price>
  </book>
  <book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6">
    <title>The Gorgias</title>
    <author>
      <name>Plato</name>
    </author>
    <price>9.99</price>
  </book>
</bookstore>

    

Return to top


Method: MemberwiseClone()
Inherited
See base class member description: System.Object.MemberwiseClone
C# Syntax:
protected object MemberwiseClone();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: MoveTo(
   XPathNavigator other
)
Summary
Moves to the same position as the specified XPathNavigator.
C# Syntax:
public abstract bool MoveTo(
   XPathNavigator other
);
Parameters:

other

The XPathNavigator positioned on the node that you want to move to.

Return Value:
true if successful; otherwise false. If false, the position of the navigator is unchanged.
Remarks
This method always returns true if other is an XPathNavigator that shares the same implementation and is pointing at the same document instance as the current navigator.

This method always returns false if other is an XPathNavigator that has a different implementation than the current navigator.

If other is an XPathNavigator that shares the same implementation but is pointing at a different document instance than the current navigator, the behavior of MoveTo varies depending on how the navigators were implemented. If the navigators were implemented over an XPathDocument, MoveTo returns true. If the navigators were implemented over either an XmlDocument or an XmlDataDocument, MoveTo returns false.

Return to top


Method: MoveToAttribute(
   string localName,
   string namespaceURI
)
Summary
Moves to the attribute with matching XPathNavigator.LocalName and XPathNavigator.NamespaceURI.
C# Syntax:
public abstract bool MoveToAttribute(
   string localName,
   string namespaceURI
);
Parameters:

localName

The local name of the attribute.

namespaceURI

The namespace URI of the attribute.

Return Value:
true if the attribute is found; otherwise, false. If false, the position of the navigator does not change.
Remarks
If the navigator is not currently positioned on an element, this method returns false.

After a successful call to MoveToAttribute, the LocalName, NamespaceURI and XPathNavigator.Prefix properties reflect the values of the attribute. When the navigator is positioned on an attribute, the methods XPathNavigator.MoveToNext, XPathNavigator.MoveToPrevious, and XPathNavigator.MoveToFirst are not applicable. These methods always return false and do not change the position of the navigator. Rather, you can call XPathNavigator.MoveToNextAttribute to move to the next attribute node.

Once positioned on an attribute, you can call XPathNavigator.MoveToParent to move to the owner element.

See also:
XPathNavigator.MoveToFirstAttribute | XPathNavigator.MoveToNextAttribute | XPathNavigator.GetAttribute

Return to top


Method: MoveToFirst()
Summary
Moves to the first sibling of the current node.
C# Syntax:
public abstract bool MoveToFirst();
Return Value:
true if the navigator is successful moving to the first sibling node; false if there is no first sibling or if the navigator is currently positioned on an attribute node.
See also:
XPathNavigator.MoveToNext | XPathNavigator.MoveToPrevious

Return to top


Method: MoveToFirstAttribute()
Summary
Moves to the first attribute.
C# Syntax:
public abstract bool MoveToFirstAttribute();
Return Value:
true if the navigator is successful moving to the first attribute; otherwise, false.
Remarks
If the navigator is not currently positioned on an element, this method returns false and the position of the navigator does not change.

After a successful call to MoveToFirstAttribute, the LocalName, NamespaceURI and XPathNavigator.Prefix properties reflect the values of the attribute. When the navigator is positioned on an attribute, the methods XPathNavigator.MoveToNext, XPathNavigator.MoveToPrevious, and XPathNavigator.MoveToFirst are not applicable. These methods always return false and do not change the position of the navigator. Rather, you can call XPathNavigator.MoveToNextAttribute to move to the next attribute node.

Once positioned on an attribute, you can call XPathNavigator.MoveToParent to move to the owner element.

See also:
XPathNavigator.MoveToAttribute | XPathNavigator.MoveToNextAttribute | XPathNavigator.GetAttribute | XPathNavigator.HasAttributes

Return to top


Method: MoveToFirstChild()
Summary
Moves to the first child of the current node.
C# Syntax:
public abstract bool MoveToFirstChild();
Return Value:
true if there is a first child node; otherwise false.
Remarks
Root and Element are the only two XPath node types that can have children. This property always returns false for all other node types.
See also:
XPathNodeType | XPathNavigator.MoveToNext | XPathNavigator.MoveToParent | XPathNavigator.HasChildren

Return to top


Overloaded Method: MoveToFirstNamespace()
Summary
Moves the XPathNavigator to first namespace node of the current element.
C# Syntax:
public bool MoveToFirstNamespace();
Return Value:
true if the navigator is successful moving to the first namespace node; otherwise false.
Remarks
If the navigator is not currently positioned on an element, this method returns false and the position of the navigator does not change.

After the navigator has been moved to the namespace node the XPathNavigator.Name property reflects the name of the namespace.

When the navigator is positioned on a namespace node, the methods XPathNavigator.MoveToNext, XPathNavigator.MoveToPrevious, and XPathNavigator.MoveToFirst are not applicable. These methods always return false and do not change the position of the navigator. Rather, you can call XPathNavigator.MoveToNextNamespace to move to the next namespace node.

Once positioned on an namespace node, call XPathNavigator.MoveToParent to move back to the element node.

For a definition of namespace nodes, see section 5.4 of the W3C XML Path Language (XPath) recommendation located at http://www.w3.org/TR/xpath#data-model .

See also:
XPathNavigator.MoveToNextNamespace | XPathNavigator.GetNamespace | XPathNavigator.MoveToNamespace

Return to top


Overloaded Method: MoveToFirstNamespace(
   XPathNamespaceScope namespaceScope
)
Summary
Moves the XPathNavigator to the first namespace node matching the XPathNamespaceScope specified.
C# Syntax:
public abstract bool MoveToFirstNamespace(
   XPathNamespaceScope namespaceScope
);
Parameters:

namespaceScope

An XPathNamespaceScope value describing the namespace scope.

Return Value:
true if the navigator is successful moving to the first namespace node; otherwise false.
Remarks
Using the following XML fragment as an example, if the navigator is positioned on the bar node, MoveToFirstNamespace behaves in the following manner.
              <root xmlns='urn:default' xmlns:a='A1' xmlns:b='B'>
                <item xmlns='' xmlns:a='A2'>
                  <bar xmlns:c='C' />
                </item>
              </root>
            

If the navigator is not currently positioned on an element, this method returns false and the position of the navigator does not change. After the navigator has been moved to the namespace node the XPathNavigator.Name property reflects the name of the namespace.

When the navigator is positioned on a namespace node, the methods XPathNavigator.MoveToNext, XPathNavigator.MoveToPrevious, and XPathNavigator.MoveToFirst are not applicable. These methods always return false and do not change the position of the navigator. Rather, you can call XPathNavigator.MoveToNextNamespace to move to the next namespace node.

Once positioned on an namespace node, call XPathNavigator.MoveToParent to move back to the element node.

For a definition of namespace nodes, see section 5.4 of the W3C XML Path Language (XPath) recommendation located at http://www.w3.org/TR/xpath#data-model .

See also:
XPathNavigator.MoveToNextNamespace | XPathNavigator.GetNamespace | XPathNavigator.MoveToNamespace

Return to top


Method: MoveToId(
   string id
)
Summary
Moves to the node that has an attribute of type ID whose value matches the specified string.
C# Syntax:
public abstract bool MoveToId(
   string id
);
Parameters:

id

A string representing the ID value of the node to which you want to move. This argument does not need to be atomized.

Return Value:
true if the move was successful; otherwise false. If false, the position of the navigator is unchanged.

Note If the navigator is implemented over an XmlDataDocument, this method always returns false and the position of the navigator is not changed.
Remarks
This method can be used to identify nodes by unique ID provided the source document explicitly declares attributes of type ID using a DTD.

For example, suppose the following XML data, <data><x a="a1"/></data> , was loaded using a DTD that included the following: <!ATTLIST x a ID #REQUIRED> .

If the navigator was positioned somewhere in the XML data, calling MoveToId("a1") positions the navigator on the element node x.

Return to top


Method: MoveToNamespace(
   string name
)
Summary
Moves the XPathNavigator to the namespace node with the specified local name.
C# Syntax:
public abstract bool MoveToNamespace(
   string name
);
Parameters:

name

The local name of the namespace node.

Return Value:
true if the move was successful; false if a matching namespace node was not found or if the navigator is not positioned on an element node.
Remarks
After the navigator has been moved to the namespace node the XPathNavigator.Name property reflects the name of the namespace.

When the navigator is positioned on a namespace node, the methods XPathNavigator.MoveToNext, XPathNavigator.MoveToPrevious, and XPathNavigator.MoveToFirst are not applicable. These methods always return false and do not change the position of the navigator. Rather, you can call XPathNavigator.MoveToNextNamespace to move to the next namespace node.

Once positioned on a namespace node, you can call XPathNavigator.MoveToParent to move back to the element node.

For a definition of namespace nodes, see section 5.4 of the W3C XML Path Language (XPath) recommendation located at http://www.w3.org/TR/xpath#data-model.

See also:
XPathNavigator.MoveToNextNamespace | XPathNavigator.MoveToFirstNamespace | XPathNavigator.GetNamespace

Return to top


Method: MoveToNext()
Summary
Moves to the next sibling of the current node.
C# Syntax:
public abstract bool MoveToNext();
Return Value:
true if the navigator is successful moving to the next sibling node; false if there are no more siblings or if the navigator is currently positioned on an attribute node. If false, the position of the navigator is unchanged.
Example
The following example walks the node tree recursively and displays information on element and text nodes.
public static void RecursiveWalk(XPathNavigator nav)
{
   switch (nav.NodeType){
     case XPathNodeType.Element:
        if (nav.Prefix==String.Empty)
          Console.WriteLine("<{0}>", nav.LocalName);
        else
          Console.Write("<{0}:{1}>", nav.Prefix, nav.LocalName);
          Console.WriteLine("\t"+ nav.NamespaceURI);
        break;
     case XPathNodeType.Text:
        Console.WriteLine("\t" + nav.Value);
        break;
    }

    if ( nav.MoveToFirstChild() )
   {
      do{
         RecursiveWalk(nav);
      } while ( nav.MoveToNext() );

      nav.MoveToParent();
      if (nav.NodeType == XPathNodeType.Element)
        Console.WriteLine("</{0}>", nav.Name);
    }
}	

    
See also:
XPathNavigator.MoveToPrevious | XPathNavigator.MoveToFirst

Return to top


Method: MoveToNextAttribute()
Summary
Moves to the next attribute.
C# Syntax:
public abstract bool MoveToNextAttribute();
Return Value:
true if the navigator is successful moving to the next attribute; false if there are no more attributes.
Remarks
If the navigator is not currently positioned on an attribute, this method returns false and the position of the navigator does not change.

When the navigator is positioned on an attribute, the methods XPathNavigator.MoveToNext, XPathNavigator.MoveToPrevious, and XPathNavigator.MoveToFirst are not applicable. These methods always return false and do not change the position of the navigator.

Once positioned on an attribute, you can call XPathNavigator.MoveToParent to move to the owner element.

Example
The following example displays all attributes on each book node.
using System;
using System.IO;
using System.Xml;
using System.Xml.XPath;

public class Sample
{
  public static void Main()
  {
    XPathDocument doc = new XPathDocument("books.xml");
    XPathNavigator nav = doc.CreateNavigator();
 
    // Select all book nodes and display all attributes on each book.
    XPathNodeIterator ni = nav.SelectDescendants("book", "", false);
    while (ni.MoveNext()){
       XPathNavigator nav2 = ni.Current.Clone();
       nav2.MoveToFirstAttribute();
       Console.WriteLine("{0} = {1}", nav2.Name, nav2.Value);
       while (nav2.MoveToNextAttribute()){
          Console.WriteLine("{0} = {1}", nav2.Name, nav2.Value);
       }
       Console.WriteLine(); 
    } 

  }
}

    
See also:
XPathNavigator.MoveToFirstAttribute | XPathNavigator.MoveToAttribute | XPathNavigator.GetAttribute | XPathNavigator.HasAttributes

Return to top


Overloaded Method: MoveToNextNamespace()
Summary
Moves the XPathNavigator to the next namespace node.
C# Syntax:
public bool MoveToNextNamespace();
Return Value:
true if the navigator is successful moving to the next namespace node; otherwise false. If false, the position of the navigator is unchanged.
Remarks
If the navigator is not currently positioned on a namespace node, this method returns false and the position of the navigator does not change.

When the navigator is positioned on a namespace node, the methods XPathNavigator.MoveToNext, XPathNavigator.MoveToPrevious, and XPathNavigator.MoveToFirst are not applicable. These methods always return false and do not change the position of the navigator.

Once positioned on an namespace node, call XPathNavigator.MoveToParent to move back to the element node.

For a definition of namespace nodes, see section 5.4 of the W3C XML Path Language (XPath) recommendation located at http://www.w3.org/TR/xpath#data-model.

See also:
XPathNavigator.MoveToFirstNamespace | XPathNavigator.GetNamespace | XPathNavigator.MoveToNamespace

Return to top


Overloaded Method: MoveToNextNamespace(
   XPathNamespaceScope namespaceScope
)
Summary
Moves the XPathNavigator to the next namespace node matching the XPathNamespaceScope specified.
C# Syntax:
public abstract bool MoveToNextNamespace(
   XPathNamespaceScope namespaceScope
);
Parameters:

namespaceScope

An XPathNamespaceScope value describing the namespace scope.

Return Value:
true if the navigator is successful moving to the next namespace node; otherwise false. If false, the position of the navigator is unchanged.
Remarks
If the navigator is not currently positioned on a namespace node, this method returns false and the position of the navigator does not change.

When the navigator is positioned on a namespace node, the methods XPathNavigator.MoveToNext, XPathNavigator.MoveToPrevious, and XPathNavigator.MoveToFirst are not applicable. These methods always return false and do not change the position of the navigator.

Once positioned on an namespace node, call XPathNavigator.MoveToParent to move back to the element node.

For a definition of namespace nodes, see section 5.4 of the W3C XML Path Language (XPath) recommendation located at http://www.w3.org/TR/xpath#data-model.

See also:
XPathNavigator.MoveToFirstNamespace | XPathNavigator.GetNamespace | XPathNavigator.MoveToNamespace

Return to top


Method: MoveToParent()
Summary
Moves to the parent of the current node.
C# Syntax:
public abstract bool MoveToParent();
Return Value:
true if there is a parent node; otherwise false.
Remarks
The following table lists the XPathNodeType and what type of parent node they may have, if any.

XPathNodeType Parent Node
Root Root nodes do not have parents.
Element Element or Root node.
Attribute Element node.
Text Element node.
Namespace Element node.
ProcessingInstruction Element or Root node.
Comment Element or Root node.
Whitespace Element or Root node.
SignificantWhitespace Element or Root node.

Return to top


Method: MoveToPrevious()
Summary
Moves to the previous sibling of the current node.
C# Syntax:
public abstract bool MoveToPrevious();
Return Value:
true if the navigator is successful moving to the previous sibling node; false if there is no previous sibling or if the navigator is currently positioned on an attribute node.
See also:
XPathNavigator.MoveToNext | XPathNavigator.MoveToFirst

Return to top


Method: MoveToRoot()
Summary
Moves to the root node to which the current node belongs.
C# Syntax:
public abstract void MoveToRoot();
Remarks
All nodes belong to one and only one document. Therefore, this method is always successful. For a definition of a root node, see section 5.1 of the W3C XML Path Language (XPath) recommendation located at http://www.w3.org/TR/xpath#data-model.

Return to top


Overloaded Method: Select(
   string xpath
)
Summary
Selects a node set using the specified XPath expression.
C# Syntax:
public virtual XPathNodeIterator Select(
   string xpath
);
Parameters:

xpath

A string representing an XPath expression.

Return Value:
An XPathNodeIterator pointing to the selected node set.
Exceptions
Exception Type Condition
ArgumentException The xpath contains an error or its return type is not a node set.
Remarks
The context for the selection is the position of the navigator when you called this method. After calling this method, the XPathNodeIterator returned represents the set of selected nodes. Use XPathNodeIterator.MoveNext on the XPathNodeIterator to walk the selected node set. Use any of the Move methods on the XPathNavigator to move within the current node tree. The XPathNavigator navigation methods are independent of the selected nodes and the XPathNodeIterator.

The following C# code walks the selected set of nodes.

              XPathNodeIterator iterator = nav.Select("/bookstore/book");
              while (iterator.MoveNext()){
               Console.WriteLine(Iterator.Current.Name);
              }
                 
            

If the XPath expression requires namespace resolution, use the overload which takes an XPathExpression as its argument.

Calling Select again returns a new XPathNodeIterator pointing to the selected set of nodes matching the new Select call. The two XPathNodeIterator objects are completely independent of each other.

This method has no effect on the state of the XPathNavigator.

Example
The following example selects and displays all title nodes.
using System;
using System.Xml.XPath;

public class Sample
{
  public static void Main()
  {

    XPathDocument doc = new XPathDocument("books.xml");
    XPathNavigator nav = doc.CreateNavigator();

    XPathNodeIterator ni = nav.Select("/bookstore/book/title");
    while (ni.MoveNext())
       Console.WriteLine(ni.Current.Value);
  }
}

    
The example uses the file, books.xml, as input.
<bookstore>
  <book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0">
    <title>The Autobiography of Benjamin Franklin</title>
    <author>
      <first-name>Benjamin</first-name>
      <last-name>Franklin</last-name>
    </author>
    <price>8.99</price>
  </book>
  <book genre="novel" publicationdate="1967" ISBN="0-201-63361-2">
    <title>The Confidence Man</title>
    <author>
      <first-name>Herman</first-name>
      <last-name>Melville</last-name>
    </author>
    <price>11.99</price>
  </book>
  <book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6">
    <title>The Gorgias</title>
    <author>
      <name>Plato</name>
    </author>
    <price>9.99</price>
  </book>
</bookstore>

    
See also:
XmlNode.SelectNodes | XmlNode.SelectSingleNode | XPathNavigator.SelectDescendants | XPathNavigator.SelectChildren | XPathNavigator.SelectAncestors

Return to top


Overloaded Method: Select(
   XPathExpression expr
)
Summary
Selects a node set using the specified XPathExpression.
C# Syntax:
public virtual XPathNodeIterator Select(
   XPathExpression expr
);
Parameters:

expr

An XPathExpression.

Return Value:
An XPathNodeIterator pointing to the selected node set.
Exceptions
Exception Type Condition
ArgumentException The expr contains an error or its return type is not a node set.
Remarks
The context for the selection is the position of the navigator when you called this method. After calling this method, the XPathNodeIterator returned represents the set of selected nodes. Use XPathNodeIterator.MoveNext on the XPathNodeIterator to walk the selected node set. Use any of the Move methods on the XPathNavigator to move within the current node tree. The XPathNavigator navigation methods are independent of the selected nodes and the XPathNodeIterator.

The following C# code walks the selected set of nodes.

              XPathNodeIterator iterator = nav.Select(expr);
              while (iterator.MoveNext()){
               Console.WriteLine(Iterator.Current.Name);
              }
                 
            

If the XPathExpression requires namespace resolution, the prefix and namespace URI pair must be added to an XmlNamespaceManager and the XPathExpression.SetContext method must be called to specify the XmlNamespaceManager to use for namespace resolution.

For example, if the document contains the XML nodes

              <bookstore xmlns:bk='urn:samples'>
                <book bk:ISBN='1-325-0980'>
                  <title>Pride And Prejudice</title>
                </book>
              </bookstore>
            

The following C# code selects the bk:ISBN node.

              XPathExpression expr = nav.Compile("book/@bk:ISBN");
              XmlNamespaceManager mngr = new XmlNamespaceManager(new NameTable());
              mngr.AddNamespace("bk","urn:samples");
              expr.SetContext(mngr);
              nav.Select(expr)
            


Note If the XPathExpression does not include a prefix, it is assumed that the namespace URI is the empty namespace. If your XML includes a default namespace, you must still use the SetContext method and provide an XmlNamespaceManager containing a prefix and namespace URI to handle the default namespace.

For example, if you had the following XML:

              <bookstore xmlns="http://www.lucernepublishing.com">
               <book>
               <title>Pride And Prejudice</title>
               </book>
              </bookstore>
            
The following C# code selects all book nodes:
              XmlNamespaceManager nsmgr = new XmlNamespaceManager(nav.NameTable);
              nsmgr.AddNamespace("ab", "http://www.lucernepublishing.com");
              XPathExpression expr;
              expr = nav.Compile("//ab:book");
              expr.SetContext(nsmgr);
              XPathNodeIterator iterator = nav.Select(expr);
            

Calling Select again returns a new XPathNodeIterator pointing to the selected set of nodes matching the new Select call. The two XPathNodeIterator objects are completely independent of each other.

This method has no effect on the state of the XPathNavigator.

Example
The following example selects all books by Jane Austen and sorts them by title.
using System;
using System.IO;
using System.Xml;
using System.Xml.XPath;

public class Sample
{
  public static void Main()
  {

      XPathDocument doc = new XPathDocument("booksort.xml");
      XPathNavigator nav = doc.CreateNavigator();

      //Select all books by Jane Austen.
      XPathExpression expr; 
      expr = nav.Compile("descendant::book[author/last-name='Austen']");

      //Sort the selected books by title.
      expr.AddSort("title", XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Text);

      //Display the selection.
      XPathNodeIterator iterator = nav.Select(expr);
      while (iterator.MoveNext()){
        XPathNavigator nav2 = iterator.Current.Clone();
        nav2.MoveToFirstChild();
        Console.WriteLine("Book title:  {0}", nav2.Value);
      }
   }

}

    

The example uses the file, booksort.xml, as input.


<?xml version="1.0"?>
<!-- a fragment of a book store inventory database -->
<bookstore xmlns:bk="urn:samples">
  <book genre="novel" publicationdate="1997" bk:ISBN="1-861001-57-8">
    <title>Pride And Prejudice</title>
    <author>
      <first-name>Jane</first-name>
      <last-name>Austen</last-name>
    </author>
    <price>24.95</price>
  </book>
  <book genre="novel" publicationdate="1992" bk:ISBN="1-861002-30-1">
    <title>The Handmaid's Tale</title>
    <author>
      <first-name>Margaret</first-name>
      <last-name>Atwood</last-name>
    </author>
    <price>29.95</price>
  </book>
  <book genre="novel" publicationdate="1991" bk:ISBN="1-861001-57-6">
    <title>Emma</title>
    <author>
      <first-name>Jane</first-name>
      <last-name>Austen</last-name>
    </author>
    <price>19.95</price>
  </book>
  <book genre="novel" publicationdate="1982" bk:ISBN="1-861001-45-3">
    <title>Sense and Sensibility</title>
    <author>
      <first-name>Jane</first-name>
      <last-name>Austen</last-name>
    </author>
    <price>19.95</price>
  </book>
</bookstore>

    
See also:
XmlNode.SelectNodes | XmlNode.SelectSingleNode | XPathNavigator.SelectDescendants | XPathNavigator.SelectChildren | XPathNavigator.SelectAncestors

Return to top


Overloaded Method: SelectAncestors(
   XPathNodeType type,
   bool matchSelf
)
Summary
Selects all the ancestor element nodes of the current node with the matching XPathNodeType.
C# Syntax:
public virtual XPathNodeIterator SelectAncestors(
   XPathNodeType type,
   bool matchSelf
);
Parameters:

type

The XPathNodeType of the ancestor nodes.

matchSelf

true to include the context node in the selection; otherwise false.

Return Value:
An XPathNodeIterator pointing to the selected nodes.
Remarks
This method has no effect on the state of the XPathNavigator.
See also:
XPathNavigator.SelectChildren | XPathNavigator.SelectDescendants | XPathNavigator.Select

Return to top


Overloaded Method: SelectAncestors(
   string name,
   string namespaceURI,
   bool matchSelf
)
Summary
Selects all the ancestor element nodes of the current node with the supplied local name and namespace URI.
C# Syntax:
public virtual XPathNodeIterator SelectAncestors(
   string name,
   string namespaceURI,
   bool matchSelf
);
Parameters:

name

The local name of the ancestor nodes.

namespaceURI

The namespace URI of the ancestor nodes.

matchSelf

true to include the context node in the selection; otherwise false.

Return Value:
An XPathNodeIterator pointing to the selected nodes.
Remarks
This method has no effect on the state of the XPathNavigator.

If name is an empty string, all ancestor nodes belonging to the specified namespace URI are selected. If namespaceURI is an empty string, all ancestor nodes with the specified name belonging to the null namespace are selected. If both name and namespaceURI are empty strings, all ancestor nodes belonging to the null namespace are selected.

Example
The following example selects all orders containing the specified CD.
using System;
using System.Xml.XPath;

public class Sample
{
  public static void Main()
  {

    XPathDocument doc = new XPathDocument("order.xml");
    XPathNavigator nav = doc.CreateNavigator();

    // Select all cd nodes with the specified ISBN value.
    XPathNodeIterator ni = nav.Select("//cd[@ISBN='2-3631-4']");

    // Select all orders containing the selected cd node.
    while (ni.MoveNext()){
       XPathNavigator nav2 = ni.Current;
       XPathNodeIterator ni2 = nav2.SelectAncestors("order", "", false);
       while (ni2.MoveNext())
         Console.WriteLine(ni2.Current.ToString());   
   }

  }
}

    
The example uses the file, order.xml, as input.
<!--Represents a customer order-->
<order>
  <book ISBN='10-861003-324'>
    <title>The Handmaid's Tale</title>
    <price>19.95</price>
  </book>
  <cd ISBN='2-3631-4'>
    <title>Americana</title>
    <price>16.95</price>
  </cd>
</order>

    
See also:
XPathNavigator.SelectChildren | XPathNavigator.SelectDescendants | XPathNavigator.Select

Return to top


Overloaded Method: SelectChildren(
   XPathNodeType type
)
Summary
Selects all the child nodes of the current node with the matching XPathNodeType.
C# Syntax:
public virtual XPathNodeIterator SelectChildren(
   XPathNodeType type
);
Parameters:

type

The XPathNodeType of the child nodes.

Return Value:
An XPathNodeIterator pointing to the selected nodes.
Remarks
This method has no effect on the state of the XPathNavigator.

The selected nodes will never contain attribute or namespace nodes.

See also:
XPathNavigator.SelectAncestors | XPathNavigator.SelectDescendants | XPathNavigator.Select

Return to top


Overloaded Method: SelectChildren(
   string name,
   string namespaceURI
)
Summary
Selects all the child element nodes of the current node with the supplied local name and namespace URI.
C# Syntax:
public virtual XPathNodeIterator SelectChildren(
   string name,
   string namespaceURI
);
Parameters:

name

The local name of the child nodes.

namespaceURI

The namespace URI of the child nodes.

Return Value:
An XPathNodeIterator pointing to the selected nodes.
Remarks
This method has no effect on the state of the XPathNavigator.

If name is an empty string, all child nodes belonging to the specified namespace URI are selected. If namespaceURI is an empty string, all child nodes with the specified name belonging to the null namespace are selected. If both name and namespaceURI are empty strings, all child nodes belonging to the null namespace are selected.

The selected nodes will never contain attribute or namespace nodes.

See also:
XPathNavigator.SelectAncestors | XPathNavigator.SelectDescendants | XPathNavigator.Select

Return to top


Overloaded Method: SelectDescendants(
   XPathNodeType type,
   bool matchSelf
)
Summary
Selects all the descendant nodes of the current node with the matching XPathNodeType.
C# Syntax:
public virtual XPathNodeIterator SelectDescendants(
   XPathNodeType type,
   bool matchSelf
);
Parameters:

type

The XPathNodeType of the descendant nodes.

matchSelf

true to include the context node in the selection; otherwise false.

Return Value:
An XPathNodeIterator pointing to the selected nodes.
Remarks
This method has no effect on the state of the XPathNavigator.

A descendant is a child or a child of a child and so on; thus, the selected nodes will never contain attribute or namespace nodes.

Example
The following example moves to the first book element and displays each of its text nodes.
using System;
using System.IO;
using System.Xml.XPath;

public class Sample
{
  public static void Main()
  {
    XPathDocument doc = new XPathDocument("books.xml");
    XPathNavigator nav = doc.CreateNavigator();
 
    // Move to the first book node.
    XPathNodeIterator ni = nav.SelectDescendants("book", "", false);
    ni.MoveNext();
    XPathNavigator nav2 = ni.Current;

    // Display the content of each element node.
    XPathNodeIterator ni2 = nav2.SelectDescendants(XPathNodeType.Text, false); 
    while (ni2.MoveNext()){
      Console.WriteLine(ni2.Current.Value);
    } 

  }
}

    
The example uses the file, books.xml, as input.
<bookstore>
  <book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0">
    <title>The Autobiography of Benjamin Franklin</title>
    <author>
      <first-name>Benjamin</first-name>
      <last-name>Franklin</last-name>
    </author>
    <price>8.99</price>
  </book>
  <book genre="novel" publicationdate="1967" ISBN="0-201-63361-2">
    <title>The Confidence Man</title>
    <author>
      <first-name>Herman</first-name>
      <last-name>Melville</last-name>
    </author>
    <price>11.99</price>
  </book>
  <book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6">
    <title>The Gorgias</title>
    <author>
      <name>Plato</name>
    </author>
    <price>9.99</price>
  </book>
</bookstore>

    
See also:
XPathNavigator.SelectAncestors | XPathNavigator.SelectChildren | XPathNavigator.Select

Return to top


Overloaded Method: SelectDescendants(
   string name,
   string namespaceURI,
   bool matchSelf
)
Summary
Selects all the descendant element nodes of the current node with the supplied local name and namespace URI.
C# Syntax:
public virtual XPathNodeIterator SelectDescendants(
   string name,
   string namespaceURI,
   bool matchSelf
);
Parameters:

name

The local name of the descendant nodes.

namespaceURI

The namespace URI of the descendant nodes.

matchSelf

true to include the context node in the selection; otherwise false.

Return Value:
An XPathNodeIterator pointing to the selected nodes.
Remarks
This method has no effect on the state of the XPathNavigator.

If name is an empty string, all descendant nodes belonging to the specified namespace URI are selected. If namespaceURI is an empty string, all descendant nodes with the specified name belonging to the null namespace are selected. If both name and namespaceURI are empty strings, all descendant nodes belonging to the null namespace are selected.

A descendant is a child or a child of a child and so on; thus the selected nodes will never contain attribute or namespace nodes.

See also:
XPathNavigator.SelectAncestors | XPathNavigator.SelectChildren | XPathNavigator.Select

Return to top


Overridden Method: ToString()
Summary
Gets the text value of the current node. This method is equivalent to returning the XPathNavigator.Value property.
C# Syntax:
public override string ToString();
Return Value:
The content returned depends on the XPathNavigator.NodeType of the node.

Node Type Value
Attribute The value of the attribute.
Element The XmlNode.InnerText of the element.
Comment The content of the comment.
ProcessingInstruction The entire content excluding the target.
Text The content of the text node.
Whitespace The white space between mark-up.
SignificantWhitespace The white space between markup in a mixed content model or white space within an xml:space= 'preserve' scope.
Root The XmlNode.InnerText of the root node.

Return to top


Top of page

Copyright (c) 2002 Microsoft Corporation. All rights reserved.