XPath from XmlNode

Posted on 2009-02-09
Last Modified: 2013-11-11
I have a .NET XmlDocument and an XmlNode from that document.  Is there an easy way to generate the XPath to that node.  I don't think I can use wildcards because I have to get a unique path to the single node.
Question by:skip_sailors
    LVL 38

    Expert Comment

    I don't think it's possible for a general "one size fits all" solution.  It's likely possible with foreknowledge of the XML structure.

    What is the structure you are trying to parse in this situation?
    LVL 96

    Accepted Solution


            private void Form1_Load(object sender, EventArgs e)
                XmlDocument document = new XmlDocument();
                XmlNode node = document.SelectSingleNode("//anakia");
                string xPath = this.BuildXPath(node);
                XmlNode test = document.SelectSingleNode(xPath);
            private string BuildXPath(XmlNode node)
                StringBuilder sb = new StringBuilder();
                while (node.ParentNode != null)
                    sb.Insert(0, "/" + node.Name);
                    node = node.ParentNode;
                return sb.ToString();

    Open in new window

    LVL 96

    Expert Comment

    by:Bob Learned

    <?xml version="1.0" ?>
    <project name="xdocs" default="site" basedir=".">

          <property name="docs.src" value="./src" />
          <property name="docs.dest" value="../doc" />

          <property name="logging-site" value="../../../site/trunk" />

          <!-- Construct classpath for building the html pages -->
          <path id="site.classpath">
                <fileset dir="${logging-site}/lib">
                      <include name="*.jar" />

          <!-- ============================ -->
          <!-- ======= New targets ======== -->
          <!-- ============================ -->

          <target name="prepareSite">
                <available classname="org.apache.velocity.anakia.AnakiaTask" property="AnakiaTask.present">
                      <classpath refid="site.classpath" />

          <target name="checkSite" depends="prepareSite" unless="AnakiaTask.present">
                <echo>AnakiaTask is not present! Please check to make sure that velocity.jar is in your classpath.</echo>

          <target name="site" depends="checkSite" if="AnakiaTask.present">
                <taskdef name="anakia" classname="org.apache.velocity.anakia.AnakiaTask">
                      <classpath refid="site.classpath" />

                <mkdir dir="${docs.dest}/css" />
                <copy file="${logging-site}/docs/css/site.css" tofile="${docs.dest}/css/site.css" />
                      excludes="empty.xml, anakia-project.xml, **/stylesheets/**"


    LVL 38

    Expert Comment

    The problem is that that doesn't work if there is more than one target/anakia nodes.  


    You can't specify a unique path in this situation using category/item.  You can specify category/item[1] or category/item[2] (sample code below)

    But this code will fail with a less regular XML structure, like ...

    Private Function GetXPath(ByVal XNode As XmlNode) As String
            Dim Path As String = String.Empty
            Dim Index As Integer = -1
            If Not XNode.ParentNode.ParentNode Is Nothing Then
                Path = GetXPath(XNode.ParentNode)
                For i As Integer = 0 To XNode.ParentNode.ChildNodes.Count - 1
                    Dim n As XmlNode = XNode.ParentNode.ChildNodes(i)
                    If XNode Is n Then
                        Index = i
                        Exit For
                    End If
            End If
            If Index > -1 Then
                Return Path & "/" & XNode.Name & String.Format("[{0}]", Index + 1)
                Return Path & "/" & XNode.Name
            End If
        End Function

    Open in new window


    Author Closing Comment

    Duplicate nodes shouldn't be a problem in my case.  I won't have to deal with the [x] position of the node.  Thank you for the help.

    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    Join & Write a Comment

    Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (…
    A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
    Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
    In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor ( If you're interested in additional methods for monitoring bandwidt…

    728 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    21 Experts available now in Live!

    Get 1:1 Help Now