假设我有一个 XML 文件,我想编辑其中的一部分。以下不起作用,可能是因为我正在编辑一个 child 的副本。
from lxml import etree as et
tree = et.parse(p_my_xml)
root = tree.getroot()
for child in root:
for entry in child.getchildren():
first_part = entry.getchildren()[1].text
second_part = entry.getchildren()[2].text
if first_part == 'some_condition'
second_part = 'something_else'
tree.write(p_my_xml, pretty_print=True)
我如何才能正确修改 XML 的某些部分,以便在树中完成更改?
最佳答案
保存对元素的引用和reset the text :
second_elm = entry.getchildren()[2]
if first_part == 'some_condition'
second_elm.text = 'something_else'
关于python - 使用 lxml 覆盖 XML 中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32826555/