We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now


XPath from XmlNode

skip_sailors asked
Medium Priority
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.
Watch Question

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?
Most Valuable Expert 2012
Top Expert 2008

        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

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Most Valuable Expert 2012
Top Expert 2008


<?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/**"


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


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.
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.