语言

使用 XPathNavigator 选择 XML 数据

XPathNavigator 类提供一组方法,用于使用 XPath 表达式在 XPathDocument 或 XmlDocument 对象中选择节点集。 选择后,可以循环访问所选的节点集。

XPathNavigator 选择方法

XPathNavigator 类提供一组方法,用于使用 XPath 表达式在 XPathDocument 或 XmlDocument 对象中选择节点集。 XPathNavigator 类还提供一组经过优化的方法,选择上级节点、子节点和子代节点的速度比使用 XPath 表达式更快。 如果选择单个节点,所选的节点集将在 XPathNodeIterator 对象或 XPathNavigator 对象中返回。

使用 XPath 表达式选择节点

要使用 XPath 表达式选择节点集,请使用下列选择方法之一。

在调用时,如果选择单个节点,这些方法将返回一组节点,您可以使用 XPathNodeIterator 对象或 XPathNavigator 对象随意浏览。

使用 XPathNodeIterator 对象浏览不会影响用于创建该对象的 XPathNavigator 对象的位置。 从 XPathNavigator 方法返回的 SelectSingleNode 对象位于单个返回的节点上,同样不会影响用于创建该对象的 XPathNavigator 对象的位置。

以下示例显示如何通过 XPathNavigator 对象创建 XPathDocument 对象、如何使用 Select 方法选择 XPathDocument 对象中的节点以及如何使用 XPathNodeIterator 对象循环访问所选的节点。

Dim document As XPathDocument = New XPathDocument("books.xml")
Dim navigator As XPathNavigator = document.CreateNavigator()
Dim nodes As XPathNodeIterator = navigator.Select("/bookstore/book")

While nodes.MoveNext()
    Console.WriteLine(nodes.Current.Name)
End While
XPathDocument document = new XPathDocument("books.xml");
XPathNavigator navigator = document.CreateNavigator();
XPathNodeIterator nodes = navigator.Select("/bookstore/book");

while(nodes.MoveNext())
{
    Console.WriteLine(nodes.Current.Name);
}

该示例使用 books.xml 文件作为输入。

<?xml version="1.0" encoding="utf-8" ?> 
<bookstore>
    <book genre="autobiography" publicationdate="1981-03-22" 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-11-17" 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-02-15" ISBN="1-861001-57-6">
        <title>The Gorgias</title>
        <author>
            <name>Plato</name>
        </author>
        <price>9.99</price>
    </book>
</bookstore>

经过优化的选择方法

SelectChildren 类的 SelectAncestors、SelectDescendants 和 XPathNavigator 方法表示通常用于检索子节点、子代节点和上级节点的 XPath 表达式。 这些方法的性能已得到优化,比相应的 XPath 表达式速度更快。 SelectChildren、SelectAncestors 和 SelectDescendants 方法基于 XPathNodeType 值或要选择的节点的本地名称和命名空间 URI 选择上级节点、子节点和子代节点。 所选的上级节点、子节点和子代节点将在 XPathNodeIterator 对象中返回。

请参阅