0

Is it possible to find xpath of any specific node of XML or XHTML file ?

For (e.g.)

    <html>
     <body>
      <div id="a">
       <div> 
       </div>
       <div class"b">
        <div>
//I want xpath of below line only
          <a id="c">Here </a>
        </div>
       </div>
      </div>
     </body>
    </html>

As shown above, if I want xpath of <a id="c">Here </a> line only. Answer should be like :- /html/body/div/div[2]/a[@id="c"] Is it possible? If yes, could you please provide code?

1
  • The real question is: Why do you want the XPath of that node? Commented Jan 29, 2014 at 13:18

1 Answer 1

1

In XPath 3.0 there is a function path() which does roughly what you want, though not precisely (how is the processor supposed to know that you want the predicate [@id="c"] included?)

It's easy enough in XSLT to do something like this:

<xsl:template match="*[@id]" mode="path">
  <xsl:next-match/>
  <xsl:value-of select="concat('[@id=&quot;', @id, '&quot;]')"/>
</xsl:template>

<xsl:template match="*[last()!=1]" mode="path">
  <xsl:next-match/>
  <xsl:text>[</xsl:text>
  <xsl:number/>
  <xsl:text>]</xsl:text>
</xsl:template>

<xsl:template match="*" mode="path">
  <xsl:apply-templates select="parent::*" mode="path"/>
  <xsl:text>/</xsl:text>
  <xsl:value-of select="name()"/>
</xsl:template>

and if you really have to do it in Java, you can either invoke the above XSLT from Java or rewrite it. For a completely general solution though, you need to worry about namespaces, and what you do about namespaces depends on why you want the path in the first place: is it intended for human readers or for software?

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.