2

这是使用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 时一样?

4

1 回答 1

3

在这段代码中,我们遍历了根节点的所有子节点之后,就没有更多的工作要做了,不能有多个根节点。所以没有必要MoveToParent(),我们可以退出。这正是代码的作用。

于 2011-11-18T17:46:15.240 回答