XPath - 根据标记计数复制结果

时间:2014-12-14 16:43:45

标签: html xpath html-table duplicates

我有一个表格,我想通过根据子表格中的行数复制标题来输入电子表格/数据库。

如果可能的话,我想避免后处理,所以我正在寻找一个XPath表达式来做到这一点。

例如:

<table>
  <tr>
    <th>Title One</th>
  </tr>
  <tr>
    <td>
      <table>
        <tr>
          <td>Row one</td>
        </tr>
        <tr>
          <td>Row Two</td>
        </tr>
        <tr>
          <td>Row Three</td>
        </tr>
        <tr>
          <td>Row Four</td>
        </tr>
      </table>
    </td>
  </tr>
</table>

从上面来看,是否有一个XPath表达式会根据子表中tr // td标签的数量返回'Title One'4次?例如:

Title One
Title One
Title One
Title One

2 个答案:

答案 0 :(得分:0)

可以通过编程方式轻松完成;在这里我使用,但逻辑可以用于您选择的任何语言:

count=$(xmllint --xpath 'count(//td[starts-with(text(), "Row")])' table.html)
for ((i=0; i<count; i++)) {
    xmllint --xpath '//table/tr/th/text()' table.html
    echo
}

输出:

Title One
Title One
Title One
Title One

答案 1 :(得分:0)

XPath 2.0或3.0可以在单个表达式中执行此操作:

for $r in 1 to count(/table/tr[2]/td/table/tr/td) return /table/tr[1]/th/string()