Question

This is an example of using XPathNavigator from Microsoft.

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();
        }
    }
}

I think this code has a bug that it doesn't execute MoveToParent() to go up to one level when there is no elements to show.

nav.MoveToFirstChild();

//Loop through all of the children.
do {
    ....
} while (nav.MoveToNext()); 

nav.MoveToParent(); <-- This seems to be missing.

However, when I compile/execute this example, it works fine with and without nav.MoveToParent().

Is MoveToParent()/MoveToFirstChild() pair necessary with XPathNavigator? Is it OK not to use MoveToParent() because the second execution of MoveToNext() works as MoveToParent() when the first execution of MoveToNext() returns false?

Was it helpful?

Solution

In this code, after we go through all of the children of the root node, there is no more work to be done, there can't be more than one root node. So there is no need to MoveToParent(), we can just exit. Which is exactly what the code does.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top