4

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

<ol>
<li>a</li>
<li>b</li>
<li>c</li>
<li>d</li>
</ol>
timgeb
  • 76,762
  • 20
  • 123
  • 145
abruski
  • 851
  • 3
  • 10
  • 27
  • possible duplicate of http://stackoverflow.com/questions/226405/find-position-of-a-node-using-xpath – Learner Jan 04 '16 at 15:56

1 Answers1

2

You can use XPath and count the preceding li siblings:

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
Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Can li[@id="something"] be used with the [. = '%s']? Thanks – abruski Jan 04 '16 at 15:48
  • @abruski sure, you can filter the desired element using text, attribute or any other method - the key trick is to use `preceding-sibling::li` to count the preceding li elements. – alecxe Jan 04 '16 at 15:49