这是使用Microsoft的 XPathNavigator 的示例。
using System;
using System.Xml;
using System.Xml.XPath;
// http://support.microsoft.com/kb/308343
namespace q308343 {
class Class1 {
static void Main(string[] args) {
XPathNavigator nav;
XPathDocument docNav;
docNav = new XPathDocument(@"Books.Xml");
nav = docNav.CreateNavigator();
nav.MoveToRoot();
//Move to the first child node (comment field).
nav.MoveToFirstChild();
do {
//Find the first element.
if (nav.NodeType == XPathNodeType.Element) {
//Determine whether children exist.
if (nav.HasChildren == true) {
//Move to the first child.
nav.MoveToFirstChild();
//Loop through all of the children.
do {
//Display the data.
Console.Write("The XML string for this child ");
Console.WriteLine("is '{0}'", nav.Value);
//Check for attributes.
if (nav.HasAttributes == true) {
Console.WriteLine("This node has attributes");
}
} while (nav.MoveToNext());
}
}
} while (nav.MoveToNext());
//Pause.
Console.ReadLine();
}
}
}
我认为这段代码有一个错误,当没有要显示的元素时,它不会执行MoveToParent()
到上一级。
nav.MoveToFirstChild();
//Loop through all of the children.
do {
....
} while (nav.MoveToNext());
nav.MoveToParent(); <-- This seems to be missing.
但是,当我编译/执行此示例时,无论有无nav.MoveToParent()
.
XPathNavigator 是否需要 MoveToParent()/MoveToFirstChild() 对?是否可以不使用MoveToParent()
,因为第二次执行与MoveToNext()
第MoveToParent()
一次执行MoveToNext()
返回 false 时一样?