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

如何在现有XML结构中添加子元素?Python实现技术问询

用Python的xml.etree.ElementTree添加XML节点的具体步骤

别担心,我来一步步带你搞定给现有XML添加带属性和文本的<item>节点这个需求~

步骤1:导入核心模块

首先得把Python内置的XML处理模块导进来:

import xml.etree.ElementTree as ET

步骤2:解析你的XML

分两种常见场景处理:

  • 场景1:XML存储在本地文件中
    直接解析文件获取根节点:
    # 替换成你的XML文件路径
    tree = ET.parse('your_xml_file.xml')
    root = tree.getroot()
    
  • 场景2:XML是字符串形式(比如从接口获取的)
    用fromstring方法解析字符串:
    xml_str = '''<data>
        <items>
            <item name="item1">....text here</item>
            <item name="item2">....another text here</item>
        </items>
    </data>'''
    root = ET.fromstring(xml_str)
    

步骤3:定位到父节点<items>

我们需要把新的<item>加到<items>下面,用find方法快速找到这个父节点:

items_node = root.find('items')

如果你的XML里有多个<items>节点,可以用findall遍历,不过看你的结构应该只有一个,find就够用啦。

步骤4:创建新的<item>节点

两种方式都可以,选你顺手的:

  • 分步创建(更直观):
    # 创建空的item元素
    new_item = ET.Element('item')
    # 设置name属性
    new_item.set('name', 'item3')
    # 添加文本内容
    new_item.text = 'text here'
    
  • 一步创建(更简洁):
    new_item = ET.Element('item', attrib={'name': 'item3'})
    new_item.text = 'text here'
    

步骤5:把新节点添加到父节点里

用append方法把新创建的<item>挂到<items>下面:

items_node.append(new_item)

步骤6:保存/输出修改后的XML

  • 如果是从文件解析的,直接保存到新文件(或覆盖原文件):
    # 保存时指定编码和XML声明,避免乱码问题
    tree.write('modified_xml_file.xml', encoding='utf-8', xml_declaration=True)
    
  • 如果是字符串解析的,转换成字符串输出或使用:
    modified_xml_str = ET.tostring(root, encoding='unicode')
    print(modified_xml_str)
    

小彩蛋:美化XML输出

默认输出的XML是紧凑格式,要是想让它更易读,可以用xml.dom.minidom来美化:

import xml.dom.minidom

def prettify_xml(element):
    rough_string = ET.tostring(element, 'utf-8')
    reparsed = xml.dom.minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="  ")

# 打印美化后的XML
print(prettify_xml(root))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:06:27