tags:

views:

100

answers:

1

Is there an XPath way of recovering directly one specific attribute of preceding sibling nodes 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.

+1  A: 

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

Dimitre Novatchev
Thanks a lot it works as expected.
Matthieu BROUILLARD