Python / XML: 使用 iter 查找元素的索引

Python / XML: Finding index of elements using iter

我希望在某些 xml 中找到元素的索引,这样我就可以使用索引 + 1 在它们之后插入。

我目前正在使用 elementtree。

文档参考了按位置寻址节点,并在索引位置插入。我想发现最后一个 <Weather> 元素的索引位置。

示例代码

import xml.etree.ElementTree as ET

xml_string = """<parentelem>
    <Weather>
        <id>1</id>
        <name>Stream 1</name>
    </Weather>
    <Weather>
        <id>2</id>
        <name>Stream 2</name>
    </Weather>
    <Setting>
        <my_setting>True</my_setting>
    </Setting>
</parentelem>"""

xml_obj = ET.fromstring(xml_string)

a_lst = list(root.iter('Weather'))
        print(a_lst) 
        #[<Element 'Weather' at 0x00000211B1F18D60>, <Element 'Weather' at 0x00000211B1F1F2C0>]

        for a in a_lst:
            print(a.index())
            #AttributeError: 'xml.etree.ElementTree.Element' object has no attribute 'index'

我也试过使用这些变体:

print(root.find('Weather[last()]').position)
print(root.find('Weather[last()]').index)

我正在努力探索如何获取元素的位置索引,但我想这一定是可能的,因为我们可以根据 location/index 查询内容,也可以根据 [=31= 插入].

预期的输出是一个数字,或一个包含数字的数组。最后一个 <Weather 标签在位置 [3]

尝试

root.find('.//Weather[last()]/name').text

或者用支持xpath更好的lxml试试:

from lxml import etree
doc = etree.XML(xml_string)
#for example:
print(doc.xpath('//Weather[last()]/name/text()'))

输出:

['Stream 2']

查找最后一个元素的位置(使用 lxml):

doc.xpath('count(//Weather[last()]/preceding-sibling::*)')+1

输出:

2.0