How do I formulate an XPath expression for obtaining the attribute value for the first input node following the a node (value A) for the following HTML:
<a href="http://www.link.com">link</a>
<input value="value A" />
<input value="value B" />
I tried:
//input[(preceding-sibling::a[1])]/@value
But this gets the value attribute for both input nodes when I only want the attribute for the node for which the a node is the nearest preceding sibling.
You’re using the
[1]predicate on the wrong node. You want the first input that has apreciding-sibling::a, not all inputs that follow the firstaelement at a given level.This should yield the right result:
//a/following-sibling::input[1]/@valueIt means: for every element
afound at any level in the document, select the firstinputelement that follows it, while being its sibling. Then read itsvalueattribute.For this input:
It returns:
EDIT
This works provided that there are no elements between
aand the firstinputthat follows it.For instance, with input like this:
value A still gets selected
If it’s OK, keep the above expression. If it’s not, modify it like this to filter other elements:
//a/following-sibling::*[1][self::input]/@valueThis selects the first following sibling of
a, no matter what the tag is and only after it’s selected does it check the actual tag. This way theinputthat’s further at the same level is not chosen.