开发者

Retrieve specific preceding sibling nodes attributes

开发者 https://www.devze.com 2022-12-31 23:47 出处:网络
Is there an XPath way of recovering directly one specific attribute of preceding sibling no开发者_StackOverflow社区des of an XML node using an XPath query?

Is there an XPath way of recovering directly one specific attribute of preceding sibling no开发者_StackOverflow社区des of an XML node using an XPath query?

In the following example, I would like to retrieve the values of the alt attribute of each img nodes that precede the div element marked with the id=marker.

<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>

For this example, I want to retrieve the values 1 2 3 4.

I use the following XPath query

//div[@id='marker']/preceding-sibling::img

in order to retrieve the node list I want

<img alt="1" src="file.gif"/>
<img alt="2" src="file.gif"/>
<img alt="3" src="file.gif"/>
<img alt="4" src="file.gif"/>

As it is a node list I can then iterate on the nodes to retrieve the attribute value I am looking for, but is there an XPath way of doing it? I would have expected to be able to write something like:

//div[@id='marker']/preceding-sibling::img@alt
or //div[@id='marker']/preceding-sibling@alt::img

but I don't even know if it is possible once you have used an XPath Axe like preceding-sibling.


Use:

//div[@id='marker']/preceding-sibling::img/@alt

This selects all attributes (attribute nodes) names alt of all img elements that are preceding siblings of some div element (anywhere in the XML document) whose id attribute has the value '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()

0

精彩评论

暂无评论...
验证码 换一张
取 消