XPathNavigator and UnderlyingObject return different objects with the same xpath

I'm a little confused about the UnderlyingObject property in the XPathNavigator.

There are 2 questions: 1) in .net version 3.5 and below, UnderlyingObject returns null by setting a valid xpath in select. 2) in .net version 4 and up, UnderlyingObject returns different instances, although the xpaths I used are the same.

The problem is demonstrated by the following code:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Xml;
    using System.Xml.XPath;

    namespace TestConsole
    {
        class Program
        {
            static void Main(string[] args)
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml("<item><name>wrench</name></item>");
                XPathDocument xdoc = new XPathDocument(new XmlNodeReader(doc));
                var nav = xdoc.CreateNavigator();
                var n1 = nav.SelectSingleNode("/item");
                var n2 = nav.SelectSingleNode("/item");

                if(n1 != n2)
                {
                    Console.WriteLine("n1 != n2");
                }

                if(n1.UnderlyingObject==null && n2.UnderlyingObject == null)
                {
                    //it steps into here in .net <= 3.5
                    Console.WriteLine("UnderlyingObject are null");
                }
                else if(n1.UnderlyingObject != n2.UnderlyingObject)
                {
                    //it steps into here in .net >= 4.0
                    Console.WriteLine("UnderlyingObject not the same");
                }

                Console.ReadLine();

            }
        }
    }

      

Displaying results when run with .net version <= 3.5

n1 != n2
UnderlyingObject are null 

      

Displaying results when run with .net version> = 4

n1 != n2
UnderlyingObject not the same 

      

In the MSDN description, I am assuming n1.UnderlyingObject == n2.UnderlyingObject as they are requested with the same xpath.

According to MSDN it is noted that

The UnderlyingObject property must preserve the object identifier and should only be used to return objects that have a one-to-one correspondence with their respective overlaid elements. The user should always get the same object on successive visits to the same node using the same XPathNavigator object or cloned.

Please, help: (

+3


source to share





All Articles