Search code examples
jqueryxmlxpathxidel

Select an XML node based on same level node attribute?


how is it possible to select a node attribute based on an attribute of another same level node? What I would like to achieve is extract the links (href value) from all nodes which are followed by node span with attribute class="body-table-news-loss", i.e. the selector should return https://finance.yahoo.com/news/inspiremd-announces-planned-recapitalization-120000752.html in the example below. I have tried

 "//tr[td/span[@class='body-table-news-loss']]/a/@href"

and similar variant thereof but I don't get the desired result as I don't know exactly how to explain the hierarchy level to the XPath selector. Many thanks for your help.

<tr>
 <td>Nov-29-17 07:00AM&nbsp;&nbsp;
 </td>
    <td align="left">
      <a href="https://finance.yahoo.com/news/inspiremd-announces-planned-
      recapitalization-120000752.html">InspireMD Announces Planned 
      Recapitalization
      </a> 
      <span class="body-table-news-loss">-51.29%</span>
    </td>
</tr>
<tr>
 <td >Nov-07-17 04:05PM&nbsp;&nbsp;
 </td>
    <td align="left">
      <a href="https://finance.yahoo.com/news/inspiremd-announces-third-
      quarter-2017-210500523.html">InspireMD Announces Third Quarter 2017 
      Results; CGuard(TM) Revenue Increases 90% Versus Same Period Last Year
      </a> 
      <span class="body-table-news-gain">+5.94%</span>
    </td>
</tr>

Solution

  • Your looking for the preceding-sibling:: axes. It selects all the sibling nodes of the context that precedes it.

    Something like this should work.

    //tr/td/span[@class='body-table-news-loss']/preceding-sibling::a/data(@href)