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

如何使用Python修改XML标签并添加属性

如何使用Python修改XML标签并为其添加属性?

可以使用Python内置的xml.etree.ElementTree库完成这个需求,无需额外安装第三方包。以下是具体实现步骤和代码示例:

实现步骤

  • 解析XML内容:读取目标XML文件(或直接解析XML字符串)
  • 修改标签名称:定位<Document_Type>元素,将其标签名改为<Document>
  • 添加属性:为修改后的<Document>元素添加Type="SPTInduk"属性
  • 保存/输出结果:将修改后的XML结构写入文件或输出为字符串

完整代码示例

处理XML文件的场景

import xml.etree.ElementTree as ET

# 解析目标XML文件
tree = ET.parse("input.xml")
root = tree.getroot()

# 定位目标元素并修改标签名
doc_type_elem = root.find("Document_Type")
if doc_type_elem is not None:
    # 修改标签名称
    doc_type_elem.tag = "Document"
    # 添加指定属性
    doc_type_elem.set("Type", "SPTInduk")

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

处理XML字符串的场景

如果XML内容以字符串形式存在,可按以下方式处理:

import xml.etree.ElementTree as ET

xml_str = '''<?xml version='1.0' encoding='utf-8'?>
<batch>
  <Document_Type>
    <Ekspor>0.0</Ekspor>
    <PPNDipungutSendiriDPP>269789662720400.0</PPNDipungutSendiriDPP>
  </Document_Type>
</batch>'''

# 解析XML字符串
root = ET.fromstring(xml_str)

# 修改标签与属性
doc_type_elem = root.find("Document_Type")
if doc_type_elem is not None:
    doc_type_elem.tag = "Document"
    doc_type_elem.set("Type", "SPTInduk")

# 格式化并输出修改后的XML字符串
ET.indent(root)  # 自动添加缩进(Python 3.9及以上版本支持)
modified_xml = ET.tostring(root, encoding='utf-8', xml_declaration=True).decode('utf-8')
print(modified_xml)

修改前后对比

修改前的XML

<?xml version='1.0' encoding='utf-8'?>
<batch>
  <Document_Type>
    <Ekspor>0.0</Ekspor>
    <PPNDipungutSendiriDPP>269789662720400.0</PPNDipungutSendiriDPP>
  </Document_Type>
</batch>

修改后的XML

<?xml version='1.0' encoding='utf-8'?>
<batch>
  <Document Type="SPTInduk">
    <Ekspor>0.0</Ekspor>
    <PPNDipungutSendiriDPP>269789662720400.0</PPNDipungutSendiriDPP>
  </Document>
</batch>

内容的提问来源于stack exchange,提问作者Lintang Gilang Pratama

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 16:15:39