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?
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.
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.
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.
Have you tried this?
//myparent/mychild[text() = 'foo']
Alternatively, you can use the shortcut for the self
axis:
//myparent/mychild[. = 'foo']
Matt said it, but the full solution:
//myparent[mychild='foo']/mychild
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With