如何用Python 3在XML子标签开头添加指定属性?
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 withset()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
- We first save all existing attributes of each
<Test>element so we don't lose them. - We clear the element's attribute list to start fresh.
- We add the
IDattribute first—this ensures it's the first attribute in the tag. - We re-add the original attributes in their original order right after
ID. - 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

