Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xpath select following node of a specific node

Tags:

xpath

based on this HTML:

< table width='300' ......>
 <tbody>
  < tr>
   < td class = 'wcheader1'> ..... </td>
  < /tr>
  < tr>
   < td class = 'wccontnetbox'>......< /td>
  < /tr>
  < tr>
   < td class = 'wccontnetbox'>......< /td>
  < /tr>
  < tr>
   < td class = 'wcheader1'> ..... </td>
  < /tr>
  < tr>
   < td class = 'wccontnetbox'>......< /td>
  < /tr>
  < tr>
   < td class = 'wccontnetbox'>......< /td>
  < /tr>
  < tr>
   < td class = 'wcheader1'> ..... </td>
  < /tr>
  < tr>
   < td class = 'wccontnetbox'>......< /td>
  < /tr>
  < tr>
   < td class = 'wccontnetbox'>......< /td>
  < /tr>
 </tbody>
</table>

I have trouble selecting only the first two <td class='wccontnetbox'> elements after the first <td class='wcheader1'> element. Is there an XPath expression to do this?

UPDATE: those elements are dynamic.

like image 237
NouNou Avatar asked Jun 08 '26 05:06

NouNou


1 Answers

Use the following expression to select the first two wccontnetbox elements after the first wcheader1:

//table/tbody/tr[td[@class='wcheader1']][2]/
    following-sibling::tr[td[@class='wccontnetbox']][position()<3]/td 

I'm using // because you don't show your full input. It would be better to use a direct path to the table (e.g. /html/body/<etc>/table...).

Use the following expression to select all nodes between the first and second wcheader1 elements:

//table/tbody/tr[td[@class='wcheader1']][1]/following-sibling::tr[
    count(.|//table/tbody/tr[td[@class='wcheader1']][2]/preceding-sibling::tr)
     =
    count(//table/tbody/tr[td[@class='wcheader1']][2]/
        preceding-sibling::tr)]/td[@class='wccontnetbox']

Note: This second expression uses the Kayessian node-set intersection formula. In general, use the following expression to find the intersection of $set1 and $set2:

$set1[count(.|$set2)=count($set2)]
like image 106
Wayne Avatar answered Jun 11 '26 07:06

Wayne