Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath to find attributes where the name starts with a given value

With this xml:

<div val1="q">a</div>
<div val2="w">b</div>
<div val3="e">c</div>
<div some="r">d</div>
<div thing="t">f</div>
<div name="y">g</div>

we want to find only

<div val1="q">a</div>
<div val2="w">b</div>
<div val3="e">c</div>

which are those nodes having an attribute where the attribute name begins with val

like image 277
dom1nga Avatar asked Nov 29 '11 09:11

dom1nga


People also ask

How do I find the first element in XPath?

Go to the First name tab and right click >> Inspect. On inspecting the web element, it will show an input tag and attributes like class and id. Use the id and these attributes to construct XPath which, in turn, will locate the first name field.

What is XPath by attribute?

Definition of XPath attribute. For finding an XPath node in an XML document, use the XPath Attribute expression location path. We can use XPath to generate attribute expressions to locate nodes in an XML document.

Which character is used in start with partial matching of an attribute in XPath?

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. Using ^ to target attributes starting with a particular text.


1 Answers

You can try this :

//div/@*[starts-with(name(.), 'val')]

if you know that you are looking for the first attribute of the div element.

Edit:

Sorry didn't realize you wanted to select the elements themselves. You could use parent::div or what you did, but the proper way of doing this would be to select directly the div themselves :

//div[@*[starts-with(name(), 'val')]]
like image 137
FailedDev Avatar answered Oct 13 '22 07:10

FailedDev