XPathNavigator.Matches Method (XPathExpression)


Determines whether the current node matches the specified XPathExpression.

Namespace:   System.Xml.XPath
Assembly:  System.Xml (in System.Xml.dll)

public virtual bool Matches(
	XPathExpression expr


Type: System.Xml.XPath.XPathExpression

An XPathExpression object containing the compiled XPath expression.

Return Value

Type: System.Boolean

true if the current node matches the XPathExpression; otherwise, false.

Exception Condition

The XPath expression cannot be evaluated.


The XPath expression is not valid.

This method has no effect on the state of the XPathNavigator. This method is identical to the XPathNavigator.Matches method, except that a XPathExpression object containing the compiled XPath expression is specified, rather than an XPath expression String.

The following example displays the titles of all novels.

XPathDocument document = new XPathDocument("books.xml");
XPathNavigator navigator = document.CreateNavigator();

// Select all book nodes.
XPathNodeIterator nodes = navigator.SelectDescendants("book", "", false);

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

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

<?xml version="1.0" encoding="utf-8" ?> 
    <book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0">
        <title>The Autobiography of Benjamin Franklin</title>
    <book genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2">
        <title>The Confidence Man</title>
    <book genre="philosophy" publicationdate="1991-02-15" ISBN="1-861001-57-6">
        <title>The Gorgias</title>

.NET Framework
Available since 1.1
Available since 4.0
Return to top