[Last Call] Learn how to a build a cloud-first strategyRegister Now


XPath from XmlNode

Posted on 2009-02-09
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.
Question by:skip_sailors
  • 2
  • 2
LVL 38

Expert Comment

ID: 23605748
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

Bob Learned earned 375 total points
ID: 23607814

        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
ID: 23607816

<?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

ID: 23611573
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

ID: 31544891
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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The Client Need Led Us to RSS I recently had an investment company ask me how they might notify their constituents about their newsworthy publications.  Probably you would think "Facebook" or "Twitter" but this is an interesting client.  Their cons…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Despite its rising prevalence in the business world, "the cloud" is still misunderstood. Some companies still believe common misconceptions about lack of security in cloud solutions and many misuses of cloud storage options still occur every day. …
Suggested Courses
Course of the Month18 days, 2 hours left to enroll

831 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