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

标签 python python-3.x lxml

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

相关文章:

python - 从数据框中删除未出现一定次数的用户名?

python - XGBClassifier 的交叉验证,用于 python 中的多类分类

python - 字典唯一组合Python列表

python - 如何在Python中将文件的行读取为列表而不是字符串

python - 如何在 Python 中对嵌套字典进行 2 次排序?

python - 使用 Django webapp 登录 Azure

python - 树搜索 - 给定树中的两个节点,检查它们是否连接 - python

python - 用python解析xpath

python lxml解析html

python - 您是否可以仅修改 XML 文件中的文本字符串并仍然保持 .docx 封装的完整性和功能?