如何使用 python elementtree 仅更改一个元素的元素文本

How to change element text of only one element with python elementtree

我有以下 xml 示例文件:

<Book>
    <Location>page10</Location>
    <Chapter>
        <Location>page11</Location>
    </Chapter>
</Book>

我想更改元素 <Location> 正下方 <book> 的文本值。 使用 findall 给出两个 'Location' 元素。 使用 find 给出第一个,这可能是正确的,但如果元素 'Chapter' 被放置在 Location 之前,我得到错误的元素。

有人有什么建议吗?

使用路径..

>>> import xml.etree.ElementTree as etree
>>> frag = '<Book><Chapter><Location>page11</Location></Chapter><Location>page10</Location></Book>'
>>> tree = etree.fromstring(frag)
>>> tree.findall('./Location')[0].text
'page10'
>>> tree.findall('./Location')[1].text
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range