2011-11-18 21 views
1

這是一個使用Microsoft的XPathNavigator的示例。是否需要XPathNavigator的MoveToParent()/ MoveToFirstChild()對?

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()的第一次執行返回false時,第二次執行MoveToNext()的作用是MoveToParent()

回答

2

在此代碼中,我們遍歷根節點的所有子節點之後,沒有更多工作要做,不能有多個根節點。所以沒有必要MoveToParent(),我們可以退出。這正是代碼所做的。