如何让我的 XPath 只在每个 table 中搜索?

How do I get my XPath to search only within each table?

我有一些 HTML 看起来像这样:

<table class="resultsTable">
    <tbody>
        <tr class="even">
            <td width="35%"><strong>Name</strong></td>
            <td>ACME ANVILS, INC</td>
        </tr>
    </tbody>
</table>

和一些如下所示的 C# 代码:

var name = document.DocumentNode
                   .SelectSingleNode("//*[text()='Name']/following::td").InnerText

很高兴 returns

ACME ANVILS, INC.

但是,有一个新问题。有问题的页面现在 return 多个结果:

<table class="resultsTable">
    <tbody>
        <tr class="even">
            <td width="35%"><strong>Name</strong></td>
            <td>ACME ANVILS, INC.</td>
        </tr>
    </tbody>
</table>
<table class="resultsTable">
    <tbody>
        <tr class="even">
            <td width="35%"><strong>Name</strong></td>
            <td>ROAD RUNNER RACES, LLC</td>
        </tr>
    </tbody>
</table>

所以现在我正在使用

var tables = document.DocumentNode.SelectNodes("//table/tbody");
foreach (var table in tables)
{
    var name = table.SelectSingleNode("//*[text()='Name']/following::td").InnerText;
    ...
}

哪个掉了,因为SelectSingleNode returns null.

如何让我的 XPath 得到实际 return 结果,只在我选择的特定 table 范围内搜索?

加上第二个table,需要进行两次调整:

  1. 更改您的绝对 XPath,

    //*[text()='Name']/following::td
    

    相对于当前 tabletbody 元素之一:

    .//*[text()='Name']/following::td
    
  2. 帐户上现在有多个 td 元素 following::轴。

    要么抢第一个,

    (.//*[text()='Name']/following::td)[1]
    

    或者,更好的是,结合使用 following-sibling:: 轴 对 td 的字符串值进行测试,而不是对文本节点进行测试,文本节点可能隐藏在中间格式元素之下:

     .//td[.='Name']/following-sibling::td
    

    另见