Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find attribute names that start with a certain pattern

Tags:

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.

like image 892
Dunderklumpen Avatar asked Nov 11 '10 00:11

Dunderklumpen


People also ask

How use contains XPath?

The syntax for locating elements through XPath- Using contains() method can be written as: //<HTML tag>[contains(@attribute_name,'attribute_value')]

How do you find an element by its attributes?

Use the querySelector() method to get a DOM element by attribute, e.g. document. querySelector('[data-id="first"]') . The querySelector method will return the first element in the document that matches the specified attribute. Here is the html for the examples in this article.

How do you locate an element by partially comparing its attributes in XPath?

We can identify elements by partially comparing to its attributes in Selenium with the help of regular expression. In xpath, there is contains () method. It supports partial matching with the value of the attributes. This method comes as useful while dealing with elements having dynamic values in their attributes.


2 Answers

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

like image 186
Dimitre Novatchev Avatar answered Oct 04 '22 03:10

Dimitre Novatchev


element/@*[substring(name(), 1,1) = "s"]

will match any attribute that starts with 's'.

The function starts-with() might look better than using substring()

like image 43
Ledhund Avatar answered Oct 04 '22 02:10

Ledhund