推荐使用 xml.etree.ElementTree 批量修改 XML:加载→定位节点→修改文本/属性→保存;支持遍历标签、条件修改、多文件处理、属性增删、子节点操作及命名空间适配。
用 Python 批量修改 XML 文件的节点内容,推荐使用 xml.etree.ElementTree(标准库,无需安装),它轻量、稳定、适合常规结构化修改。核心思路是:加载 → 定位节点 → 修改文本或属性 → 保存回文件。
适用于统一修改某类标签(如所有 .text 是节点的直接子文本,不包含子元素内容。
tree.findall('.//tag_name') 或 tree.iter('tag_name') 遍历目标节点node.text = "新内容"
当有一批 XML 文件(如 data_001.xml、data_002.xml…),且要统一修改固定 XPath 路径下的节点(例如 /root/product/price),可结合 os.listdir() 或 glob.glob() 批量处理:
for file in glob.glob("*.xml"): 获取文件列表ET.parse(file) 加载,修改后调用 tree.write(file, encoding='utf-8', xml_declaration=True) 覆盖保存
shutil.copy(file, file + ".bak"))再操作不止改文字,还能批量操作属性和结构:
node.set('id', 'new_id') 或 node.attrib['status'] = 'active'
node.set('updated', '2025-06-15')
parent.remove(child_node)
new_elem = ET.SubElement(parent, 'remark'); new_elem.text = 'processed'
如果XML有命名空间(如 xmlns="http://example.com/ns"),直接用 tag 名会找不到节点。解决方法:
ns = {'ns': 'http://example.com/ns'}
tree.find('.//ns:product', ns) 或 tree.iterfind('.//ns:name', ns)
ET.register_namespace('', 'http://example.com/ns') 可避免写入时被转义为 ns0: