Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath selection by innertext

Tags:

xml

xpath

I'm trying to extract an element with a particular innertext from a parsed XML document. I know that I can select an element that has a child with a particular innertext using //myparent[mychild='foo'], but I actually just want to select the "mychild" element in this example.

<myparent>   <mychild>     foo   </mychild> </myparent> 

What would be the XPath query for "foo" that would return the "mychild" node?

like image 986
kdt Avatar asked Jan 04 '10 10:01

kdt


People also ask

Can we use text () in XPath?

5) XPath Text() FunctionThe XPath text() function is a built-in function of selenium webdriver which is used to locate elements based on text of a web element. It helps to find the exact text elements and it locates the elements within the set of text nodes. The elements to be located should be in string form.

How do I select text in XPath?

Do note that /html/text() doesn't select all text nodes in the document -- only the text nodes that are children (not descendents) of the top, html element. You probably want /html//text() . Some knowledge and understanding of XPath is typically required in order to construct XPath expressions.

How do you select a child element in XPath?

For the div element with an id attribute of hero //div[@id='hero'] , these XPath expression will select elements as follows: //div[@id='hero']/* will select all of its children elements. //div[@id='hero']/img will select all of its children img elements. //div[@id='hero']//* will select all of its descendent elements.


2 Answers

Have you tried this?

//myparent/mychild[text() = 'foo'] 

Alternatively, you can use the shortcut for the self axis:

//myparent/mychild[. = 'foo'] 
like image 146
glmxndr Avatar answered Oct 19 '22 05:10

glmxndr


Matt said it, but the full solution:

//myparent[mychild='foo']/mychild 
like image 30
Pål Thingbø Avatar answered Oct 19 '22 05:10

Pål Thingbø