Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath Get first element of subset

Tags:

I have XML like this:

<AAA>     <BBB aaa="111" bbb="222">         <CCC/>         <CCC xxx="555" yyy="666" zzz="777"/>     </BBB>     <BBB aaa="999">         <CCC xxx="qq"/>         <DDD xxx="ww"/>         <EEE xxx="oo"/>     </BBB>     <BBB>         <DDD xxx="oo"/>     </BBB> </AAA> 

I want to get first <CCC> element. But with XPath expression //*/CCC[1] I have got two <CCC> elements. Each of them is the first elemet in <BBB></BBB> context. How to get first element in subset?

like image 859
Stas Avatar asked Apr 11 '11 12:04

Stas


People also ask

How do you select the first element in XPath?

Find the first element by CSS selector. Find the first element by tag name. Find the first element by partial link text. In order to get the first element of an ID or name of an element, we can use the XPath to display the first value of an element.

How do I select the first child in XPath?

The key part of this XPath is *[1] , which will select the node value of the first child of Department .

How do you select the second element with the same XPath?

//div[@class='content'][2] means: Select all elements called div from anywhere in the document, but only the ones that have a class attribute whose value is equal to "content". Of those selected nodes, only keep those which are the second div[@class = 'content'] element of their parent.

What is text () in XPath?

XPath text() function is a built-in function of the Selenium web driver that locates items based on their text. It aids in the identification of certain text elements as well as the location of those components within a set of text nodes. The elements that need to be found should be in string format.


2 Answers

This one should work for you:

(//*/CCC)[1] 
like image 194
Lasse Espeholt Avatar answered Sep 20 '22 16:09

Lasse Espeholt


I want to get first element. But with XPath expression //*/CCC[1] I have got two elements. Each of them is the first elemet in <BBB></BBB> context. How to get first element in subset?

This is a FAQ:

The [] operator has a higher precedence (binds stronger) than the // abbreviation.

Use:

(//CCC)[1] 

This selects the first (in document order) CCC element in the XML document.

like image 29
Dimitre Novatchev Avatar answered Sep 19 '22 16:09

Dimitre Novatchev