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

如何用Python 3在XML子标签开头添加指定属性?

How to Add Attributes to the Beginning of XML Tags in Python

I get it, you're trying to prepend an ID attribute to the start of your <Test> tags, but both the standard xml.etree.ElementTree and lxml libraries are putting it either at the end or sorting it alphabetically—super frustrating when you need a specific output format. Let's fix this.

Why This Happens

  • Standard xml.etree.ElementTree: Even though Python 3.7+ preserves dictionary insertion order, this library still sorts attributes alphabetically when serializing XML, so you can't control the order with regular methods.
  • lxml: By default, new attributes added with set() get appended to the end of the attribute list, which isn't what you want here.

The Solution: Reorder Attributes with lxml

Since lxml respects the order of attribute insertion during serialization, we can manually rebuild the attribute list to put ID first:

from lxml import etree as ET

# Parse the input XML
tree = ET.parse('sample.xml')
root = tree.getroot()

for test in root.iter('Test'):
    # Save all existing attributes to a temporary dict
    original_attrs = test.attrib.copy()
    # Clear the current attributes of the element
    test.attrib.clear()
    # Add the ID attribute first
    test.set('ID', 'Hello')
    # Re-add the original attributes in their original order
    for key, value in original_attrs.items():
        test.set(key, value)

# Write the modified XML to file (preserve encoding and declaration)
tree.write('output.xml', encoding='utf-8', xml_declaration=True)

What This Does

  1. We first save all existing attributes of each <Test> element so we don't lose them.
  2. We clear the element's attribute list to start fresh.
  3. We add the ID attribute first—this ensures it's the first attribute in the tag.
  4. We re-add the original attributes in their original order right after ID.
  5. Finally, we write the modified tree to a file with proper encoding.

Result

Running this code will produce exactly the output you're expecting:

<data>
  <Test ID="Hello" Name="A" Class="1"/>
  <Test ID="Hello" Name="B" Class="2"/>
  <Test ID="Hello" Name="C" Class="3"/>
</data>

Note

Keep in mind that according to the XML specification, attribute order doesn't affect the semantic meaning of the document. But if you have strict formatting requirements (like for readability or compliance with a specific tool), this method works perfectly.

内容的提问来源于stack exchange,提问作者Dr. Essen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:42:49