简体   繁体   中英

java : finding absolute xpath of specific node

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

For (eg)

    <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 pls provide code ? Thanks in advanced. :)

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM