movetopparent ()/MoveToFirstChild()对XPathNavigator是必需的吗?

本文关键字:XPathNavigator MoveToFirstChild movetopparent | 更新日期: 2023-09-27 18:15:12

这是一个使用微软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();
        }
    }
}

我认为这段代码有一个bug,当没有元素显示时,它没有执行MoveToParent()上升到一个级别。

nav.MoveToFirstChild();
//Loop through all of the children.
do {
    ....
} while (nav.MoveToNext()); 
nav.MoveToParent(); <-- This seems to be missing.

但是,当我编译/执行这个例子时,无论是否使用nav.MoveToParent(),它都可以正常工作。

是movetopparent ()/MoveToFirstChild()对必要的XPathNavigator?是否可以不使用MoveToParent(),因为MoveToNext()的第二次执行作为MoveToParent(),当MoveToNext()的第一次执行返回false?

movetopparent ()/MoveToFirstChild()对XPathNavigator是必需的吗?

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