如何替换XML元素中的文本?

Dav*_*542 2 python xml lxml

给出以下xml:

<!-- file.xml -->
<video>
    <original_spoken_locale>en-US</original_spoken_locale>
    <another_tag>somevalue</another_tag>
</video>
Run Code Online (Sandbox Code Playgroud)

替换<original_spoken_locale>标签内部值的最佳方法是什么?如果我确实知道价值,我可以使用类似的东西:

with open('file.xml', 'r') as file:
    contents = file.read()
new_contents = contents.replace('en-US, 'new-value')
with open('file.xml', 'w') as file:
    file.write(new_contents)
Run Code Online (Sandbox Code Playgroud)

但是,在这种情况下,我不知道它的价值.

bra*_*zzi 8

使用ElementTree相当容易.只需替换text元素属性的值:

>>> from xml.etree.ElementTree import parse, tostring
>>> doc = parse('file.xml')
>>> elem = doc.findall('original_spoken_locale')[0]
>>> elem.text = 'new-value'
>>> print tostring(doc.getroot())
<video>
    <original_spoken_locale>new-value</original_spoken_locale>
    <another_tag>somevalue</another_tag>
</video>
Run Code Online (Sandbox Code Playgroud)

这也更安全,因为您可以en-US在文档的其他位置.