Margaret
Margaret

Reputation: 21

Xpath: extract value from element using text outside of element

I want to extract the @name values for the input elements below.

<div style="style info">
<input type="checkbox" name="name1" onchange="doSomething;"/>
Mobile
<br/>
<input type="checkbox" name="name2" onchange="doSomething;"/>
Event
<br/>
</div>

In the above example, I want to extract the name ("name1") that relates to "Mobile".

I need a one-line xpath that can retrieve this information for me. I have tried

//div[normalize-space(text())='Mobile']/preceding-sibling::input/@name

//div[normalize-space(text())='Mobile']/input/@name

//div[normalize-space(.)='Mobile']/preceding-sibling::input/name

and several other guesses after combing the archives here, but I have not found anything that works (I am somewhat new to XML, as you can no doubt tell; sorry if my guesses seem haphazard).

Thanks in advance for your answers, and please let me know if there are any clarifications or corrections I can make that will assist in solving this. Your help is extremely appreciated!

NOTE: XSLT is not an option for me

Upvotes: 2

Views: 1315

Answers (2)

Jirka Š.
Jirka Š.

Reputation: 3428

Try

//div/input[normalize-space(following-sibling::text()[1])='Mobile']/@name

Upvotes: 1

Justin Ko
Justin Ko

Reputation: 46846

You want to locate the text node of interest first, rather than the div. From there, you can go to the preceding-sibling as you have tried.

Try:

//text()[normalize-space() = "Mobile"]/preceding-sibling::input/@name

Upvotes: 1

Related Questions