Reputation: 1874
I am looking to find all attributes of an element that match a certain pattern.
So for an element
<element s2="1" name="aaaa" id="1" />
<element s3="1" name="aaaa" id="2" />
I would like to be able to find all attributes that start with 's' (returning the value of s1 for the first element and s3 for the value of the second element).
If this is outside of xpath's ability please let me know.
Upvotes: 24
Views: 21785
Reputation: 760
None from above worked for me. So I did not some changes and it worked for me. :)
/*:UserCustomField[starts-with(@name, 'purchaseDate')]
Upvotes: 0
Reputation: 4561
I've tested the given answers from both @Dimitre-Novatchev and @Ledhund, using lxml.html module in Python.
Both element/@*[starts-with(name(), 's')]
and element/@*[substring(name(), 1,1) = "s"]
return only the values of s2 and s3. You won't be able to know which value belong to which attribute.
I think in practice I would be more interested in finding the elements themselves that contain the attributes of names starting with specific characters rather than just their values.
To achieve that is very simple, just add /..
at the end,
element/@*[starts-with(name(), "s")]/..
or
element/@*[starts-with(name(), "s")]/parent::*
or
element/@*[starts-with(name(), "s")]/parent::node()
Upvotes: 3
Reputation: 1246
element/@*[substring(name(), 1,1) = "s"]
will match any attribute that starts with 's'.
The function starts-with()
might look better than using substring()
Upvotes: 4
Reputation: 243579
Use:
element/@*[starts-with(name(), 's')]
This XPath expression selects all atribute nodes whose name starts with the string 's'
and that are attributes of elements named element
that are children of the current node.
starts-with()
is a standard function in XPath 1.0
Upvotes: 41