Find the number (position) of the node list in the list

In xpath, how can I find which number (depending on where, 0 or 1 you start, c is 2 or 3), for example, element c has the following list:

<ol>
<li>a</li>
<li>b</li>
<li>c</li>
<li>d</li>
</ol>
+4
source share
1 answer

You can use XPath and read previous lisiblings :

count(//ol/li[. = 'c']/preceding-sibling::*)

Demo (using lxml.etree):

>>> from lxml import etree as ET
>>> data = """
... <ol>
... <li>a</li>
... <li>b</li>
... <li>c</li>
... <li>d</li>
... </ol>
... """
>>> tree = ET.fromstring(data)
>>> value = "c"
>>> int(tree.xpath("count(//ol/li[. = '%s']/preceding-sibling::li)" % value))
2
+2
source

Source: https://habr.com/ru/post/1622760/


All Articles