You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用ElementTree修改XML中多个同名元素的文本

批量修改XML中重复元素的文本内容

我的XML文件里有两处<factor-apply>1.2</factor-apply>,需要把这两处的文本都改成<factor-apply>0.5</factor-apply>。

最初用这段代码只修改了第一个元素:

import xml.etree.ElementTree as ET
xml_tree = ET.parse("TestXML.xml")
root = xml_tree.getroot()
root.find(".//{*}factor-apply").text = "0.5" 
ET.tostring(root)

尝试用findall直接修改时出现错误:

root.findall(".//{*}factor-apply").text = "0.5"

错误信息:

AttributeError                            Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_5072\1499665917.py in <module>
      3 xml_tree = ET.parse(TestXML.xml)
      4 root = xml_tree.getroot()
----> 5 root.findall(".//{*}factor-apply").text = "0.5" 
      6 ET.tostring(root)

AttributeError: 'list' object has no attribute 'text'

问题原因

  • find()方法仅返回第一个匹配到的元素,所以只能修改第一个<factor-apply>。
  • findall()方法返回所有匹配元素的列表,列表本身没有text属性,直接赋值会报错。

可行解决方案

需要通过循环遍历findall返回的元素列表,逐个修改每个元素的文本内容。以下是完整可运行的代码:

import xml.etree.ElementTree as ET

# 解析XML文件
xml_tree = ET.parse("TestXML.xml")
root = xml_tree.getroot()

# 遍历所有匹配的元素,批量修改文本
for elem in root.findall(".//{*}factor-apply"):
    elem.text = "0.5"

# 保存修改后的XML(必须执行这一步才能将改动写入文件)
xml_tree.write("modified_TestXML.xml", encoding="utf-8", xml_declaration=True)

通用化方案(适用于其他重复元素)

可以封装成一个函数,方便后续处理其他重复元素(比如多次出现的出生日期元素):

import xml.etree.ElementTree as ET

def batch_modify_xml_elements(xml_path, element_xpath, target_text, output_path=None):
    """
    批量修改XML中指定路径的所有元素文本
    :param xml_path: 原始XML文件路径
    :param element_xpath: 目标元素的XPath表达式
    :param target_text: 要设置的目标文本
    :param output_path: 修改后文件的保存路径,默认覆盖原文件
    """
    xml_tree = ET.parse(xml_path)
    root = xml_tree.getroot()
    
    for elem in root.findall(element_xpath):
        elem.text = target_text
    
    # 确定保存路径
    save_path = output_path if output_path else xml_path
    xml_tree.write(save_path, encoding="utf-8", xml_declaration=True)

# 示例:修改factor-apply元素
batch_modify_xml_elements("TestXML.xml", ".//{*}factor-apply", "0.5")

# 示例:修改出生日期元素(假设XPath是".//{*}birth-date")
# batch_modify_xml_elements("TestXML.xml", ".//{*}birth-date", "1990-01-01")

内容的提问来源于stack exchange,提问作者Mark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 05:02:53