Home > Net >  Select first child of a particular element with Xpath
Select first child of a particular element with Xpath

Time:11-12

I'm trying to get the first child element (doesn't matter what type of element it is) of a particular element, and this is what I have:

//main[@id='main2']/*[first()]

I've also tried:

//main[@id='main2']/*[1]

Both are returning null, and I know the first child is not null, so I'm just wondering what's wrong with the expression and/or how I would go about getting the first child of the //main[@id='main2'] element. I've tried Googling for some time, but to no avail.

CodePudding user response:

There is no first() XPath function; use [1] instead, as you do in your second XPath. (There is, however, a last() function.)

This XPath,

//main[@id='main2']/*[1]

selects the first element child of the main2 main element. To select the first node (element, text, comment, or processing instruction), use the node() test rather than *:

//main[@id='main2']/node()[1]

If the first XPath is selecting nothing, then there are no element children of the targeted main element. If you still find your results to be confusing, post your XML so that we can guide you more specifically regarding what you're seeing.

  • Related