Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7440383
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T10:50:37+00:00 2026-05-29T10:50:37+00:00

If I have an XPathNavigator positioned on a node, how can I get an

  • 0

If I have an XPathNavigator positioned on a node, how can I get an XPath expression that represents the path to that node, from the root?

For example, if the XML is:

<data>
    <class name='dogs'>
        <item name='doberman />
        <item name='husky' />
    </class>
    <class name='cats'>
        <item name='persian' />
        <item name='tabby' />
    </class> </data>
</data>

…then the path to the persian cat could be expressed as /data/class[2]/item[1]

I can enumerate the ancestors of the node in question with SelectAncestors() (or I could iteratively climb up the parent relationship with SelectParent()), but that doesn’t get me the positional information.

Would I have to evaluate an XPath using position() for each ancestor, or is there a better way to do this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T10:50:37+00:00Added an answer on May 29, 2026 at 10:50 am

    Assuming you’re interested only in the xpath of xml elements, I implemented a brute force algorithm (i.e. traversing the XML structure) as extension methods on XmlElement. This is very similar to @Zenexer’s answer, although I had already started on my own version when he posted his.

    Also, intrigued by Alexei’s tip about performance, I created a sort of test case using a somewhat complex XML file lyring around here. Then I implemented two versions of the same algorithm; one that depends on PreviousSibling, and other that iterates nodes sequentially. A third version relied on XPath’s position() function, but it didn’t work as expected and was discarded.

    While you should check for yourself, in my machine the results showed a significant performance advantage for the iterative version — 1.7s against 21s scored by the siblings version.

    Importart: these extension methods are declared inside a static class XmlElementExtension.

    PreviousSibling version

        public static string GetXPath_UsingPreviousSiblings(this XmlElement element)
        {
            string path = "/" + element.Name;
    
            XmlElement parentElement = element.ParentNode as XmlElement;
            if (parentElement != null)
            {
                // Gets the position within the parent element, based on previous siblings of the same name.
                // However, this position is irrelevant if the element is unique under its parent:
                XPathNavigator navigator = parentElement.CreateNavigator();
                int count = Convert.ToInt32(navigator.Evaluate("count(" + element.Name + ")"));
                if (count > 1) // There's more than 1 element with the same name
                {
                    int position = 1;
                    XmlElement previousSibling = element.PreviousSibling as XmlElement;
                    while (previousSibling != null)
                    {
                        if (previousSibling.Name == element.Name)
                            position++;
    
                        previousSibling = previousSibling.PreviousSibling as XmlElement;
                    }
    
                    path = path + "[" + position + "]";
                }
    
                // Climbing up to the parent elements:
                path = parentElement.GetXPath_UsingPreviousSiblings() + path;
            }
    
            return path;
        }
    

    Iterative version

        public static string GetXPath_SequentialIteration(this XmlElement element)
        {
            string path = "/" + element.Name;
    
            XmlElement parentElement = element.ParentNode as XmlElement;
            if (parentElement != null)
            {
                // Gets the position within the parent element.
                // However, this position is irrelevant if the element is unique under its parent:
                XmlNodeList siblings = parentElement.SelectNodes(element.Name);
                if (siblings != null && siblings.Count > 1) // There's more than 1 element with the same name
                {
                    int position = 1;
                    foreach (XmlElement sibling in siblings)
                    {
                        if (sibling == element)
                            break;
    
                        position++;
                    }
    
                    path = path + "[" + position + "]";
                }
    
                // Climbing up to the parent elements:
                path = parentElement.GetXPath_SequentialIteration() + path;
            }
    
            return path;
        }
    

    The test case

        private static void Measure(string functionName, int iterations, Action implementation)
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();
    
            for (int i = 0; i < iterations; i++)
            {
                implementation();
            }
    
            watch.Stop();
            Console.WriteLine("{0}: {1}ms", functionName, watch.ElapsedMilliseconds);
        }
    
        private static void Main(string[] args)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(@"location of some large and complex XML file");
    
            string referenceXPath = "/vps/vendorProductSets/vendorProductSet/product[100]/prodName/locName";
    
            Measure("UsingPreviousSiblings", 10000,
                    () =>
                        {
                            XmlElement target = doc.SelectSingleNode(referenceXPath) as XmlElement;
                            Debug.Assert(referenceXPath == target.GetXPath_UsingPreviousSiblings());
                        });
    
            Measure("SequentialIteration", 10000,
                    () =>
                    {
                        XmlElement target = doc.SelectSingleNode(referenceXPath) as XmlElement;
                        Debug.Assert(referenceXPath == target.GetXPath_SequentialIteration());
                    });
        }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a XPath expression that is supposed to return/get only one node out
I have an XML file like below , using xpath and xnavigator how can
Given the following XML markup: <root xmlns=Demo> <child name=foo/> </root> and an XPathNavigator positioned
I'm looking for a .NET XPathNavigator that can read XML without loading the entire
I have XML document which is something like <X><Y><Values><double>1.0</double><double>2.0</double></Values>... I am trying to get
Currently I have some legacy ASP.NET 2.0 code that uses the ASP Xml web
I have an XPathNavigator object pointing to an XML element. I want to rename
I have an XML document (an InfoPath form) that looks similar to this: <my:ClientMaintenance
We have an XML file with a very simple implementation of XLink : <root
I have an XML file that starts like this: <Elements name=Entities xmlns=XS-GenerationToolElements> I'll have

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.