使用 XPathNavigator 选择 XML 数据

更新:November 2007

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

XPathNavigator 选择方法

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

使用 XPath 表达式选择节点

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

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

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

以下示例显示如何通过 XPathDocument 对象创建 XPathNavigator 对象、如何使用 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 文件作为输入。

<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>

经过优化的选择方法

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

请参见

概念

使用 XPath 数据模型处理 XML 数据

使用 XPathNavigator 计算 XPath 表达式

使用 XPathNavigator 匹配节点

XPath 查询识别的节点类型

XPath 查询和命名空间

已编译的 XPath 表达式

参考

XmlDocument

XPathDocument

XPathNavigator