【问题标题】:how to select xml node using near element如何使用近元素选择xml节点
【发布时间】:2009-11-04 17:54:48
【问题描述】:
使用 XPath 和 HTML Agility Pack,我需要使用 color:#ff00ff 选择 destination 文本。
我的 HTML 如下所示:
<table>
<tr style="color:#ff00ff">
<td></td>
</tr>
<tr>
<td>destination</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>not destination</td>
</tr>
</table>
【问题讨论】:
标签:
xml
xpath
html-agility-pack
【解决方案1】:
/table/tr[@style = "color:#ff00ff"]/following-sibling::tr[1]/td[1]/text()
选择具有style="color:#ff00ff" 的<tr>,然后从那里开始,第一个<td> 子级<tr> 的第一个子级的文本。
为了更加安全,您可以使用:
tr[translate(@style, ' ', '') = "color:#ff00ff"]
这会从属性值中删除任何空格,因此事情变得更加独立于 HTML 源代码。
【解决方案2】:
使用 jQuery,它可能看起来像这样:
$('tr[style*="color:#ff00ff"]').next('tr').children().text();
不过,这在很大程度上取决于您的确切文档结构和样式定义。它将找到任何具有包含字符串“color:#ff00ff”(确切地说,没有空格等)的样式的 tr。然后它将从该行中选择下一个同级行并从它的所有直接子级中获取文本内容。在您的情况下,这将是单列元素。