是否有一种XPath方法使用XPath查询直接恢复XML节点的前一个兄弟节点的一个特定属性?
在以下示例中,我想检索在 div
元素标记为 id=marker
之前的每个 img
节点的 alt
属性的值 .
<content>
<img alt="1" src="file.gif" />
<img alt="2" src="file.gif" />
<img alt="3" src="file.gif" />
<img alt="4" src="file.gif" />
<div id='marker'></div>
</content>
对于此示例,我想检索值 1 2 3 4
.
我使用以下XPath查询
//div[@id='marker']/preceding-sibling::img
为了检索我想要的节点列表
<img alt="1" src="file.gif"/>
<img alt="2" src="file.gif"/>
<img alt="3" src="file.gif"/>
<img alt="4" src="file.gif"/>
由于它是一个节点列表,我可以在节点上迭代以检索我正在寻找的属性值,但是有一种XPath方式吗?我原以为能够写下这样的东西:
//div[@id='marker']/preceding-sibling::img@alt
or //div[@id='marker']/preceding-sibling@alt::img
但是,一旦你使用了像前兄弟那样的 XPath Axe
,我甚至不知道是否可能 .
1 回答
Use :
//div[@id='marker']/preceding-sibling::img/@alt
这将选择所有
img
元素的所有属性(属性节点)名称alt
,这些元素位于某些div
元素(XML文档中的任何位置)的兄弟节点之前,其id
属性的值为'marker'
.In XPath 2.0 you can even obtain a sequence of strings that are the values of these alt attributes :
//div[@id='marker']/preceding-sibling::img/@alt/string()