XPath: create relative expression from root of node to specified node?

How can I generate the required XPath expression to go from the given root to the specified node by xml structure?

I will get an HTML snippet of the table at runtime. I need to find the desired node based on some criteria and form an XPath row from the root of the node table on this node and return it.

The structure of the HTML table is not known in advance. Is there any API in Java that returns an XPath string with node root and child node?

+3
source share
4 answers

Groovy, GPATH ( xpath groovy.) groovy , Java (groovy java).

, ... HTML DOM "" (, div) id (, unique_id_for_tag) , .

HTML.body.'**'.findAll {  it.name() == 'tag' && it["@id"] == 'tag_name' }.each { 
//"it" is the return value
if(it.td[0].text().toString().trim().contains('Hello')){
   var x = it.td[0].text().toString().trim();
}
+1

( ), .

  • DOM XML
  • Node Node "//" XPATH
  • Node 2, getParentNode() xpath
+1

() XPath 1.0.

XPath 2.0:

if(not($vStart intersect $vTarget/ancestor::*))
  then ()
  else
   for $vPath in
      string-join
          ((for $x in
                $vTarget
                  /ancestor-or-self::*[. >> $vStart]
                    /concat(name(.),
                            for $n in name(.),
                                $cn in count(../*[name(.) eq $n])
                             return
                               if($cn ge 2)
                                 then concat('[', 
                                               count((preceding-sibling::*
                                                              [name() eq $n]) +1, 
                                             ']')
                                 else (),
                            '/'
                               )
               return $x),
              ''
           )
           return string-join((concat(name($vStart), '/'),$vPath), '')

XPath 2.0 XML-:

<table>
  <tr>
    <td><b>11</b></td>
    <td><i>12</i></td>
  </tr>
  <tr>
    <td><p><b>21</b></p></td>
    <td><p><b>221</b></p><p><b><i>222</i></b></p></td>
  </tr>
  <tr>
    <td><b>31</b></td>
    <td><i>32</i></td>
  </tr>
</table>

, :

  <xsl:variable name="vStart" select="/*"/>
  <xsl:variable name="vTarget" select="/*/tr[2]/td[2]/p[2]/b/i"/>

XPath 2.0 :

table/tr[2]/td[2]/p[2]/b/i/
+1

, , , "/root//child". , , , . ?

0

Source: https://habr.com/ru/post/1783623/


All Articles