CJ7 CJ7 - 5 months ago 11
HTML Question

XPath to get only children in <UL> structure

...
<ul>
<li>A
<ul>
<li>B
</li>
</ul>
</li>
<li>C
</li>
</ul>
...


What
XPath
expression will give only the child
<li>
elements of the outer
<ul>
element? I don't want the grandchild
<li>
whose value is
B
.

So far I have
//ul[1]/li
but this is giving me the grandchild as well.

Answer

Select the outer ul, and then select child li :

/ul/li

In case ul is not the root element in the actual HTML, or if you want to literally select the outer ul i.e ul that doesn't have ancestor other ul element, then you can do as follow :

//ul[not(ancestor::ul)]/li

If there is only one outer-most ul i.e the ul has no sibling ul or any other ul at the same level, you can use :

(//ul)[1]/li
Comments