gpt4 book ai didi

python - 使用 lxml 覆盖 XML 中的文本

转载 作者:太空宇宙 更新时间:2023-11-04 10:19:59 24 4
gpt4 key购买 nike

假设我有一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com