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

求助:Python修改XML指定节点值的正确脚本(现有脚本失效)

正确修改XML指定节点的Python脚本

可以使用Python标准库中的xml.etree.ElementTree来完成需求,以下是可直接运行的脚本,包含节点查找、修改和保存的完整流程:

import xml.etree.ElementTree as ET

# 加载目标XML文件
tree = ET.parse('your_file.xml')
root = tree.getroot()

# 修改<ConnectString>节点的值
connect_string_node = root.find('.//ConnectString')
if connect_string_node is not None:
    connect_string_node.text = 'my_string'
else:
    print("未找到<ConnectString>节点")

# 修改Key属性为CAT_URL的<Variable>节点值
for variable_node in root.findall('.//Variable'):
    if variable_node.get('Key') == 'CAT_URL':
        variable_node.text = 'MY_URL'
        break
else:
    print("未找到Key为CAT_URL的<Variable>节点")

# 保存修改后的XML文件
tree.write('modified_file.xml', encoding='utf-8', xml_declaration=True)
print("XML文件修改完成")

关键说明:

  • 用.//ConnectString的XPath表达式,可递归查找XML所有层级的目标节点,无需限定节点所在的固定层级
  • 遍历<Variable>节点时,通过get('Key')读取属性值来精准匹配目标节点
  • 加入节点存在性判断,避免因节点缺失导致脚本运行报错
  • tree.write方法指定编码和XML声明参数,确保输出文件格式规范、编码正确

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 10:20:55