Dr. Essen
Dr. Essen

Reputation: 621

Add attribute at the beginning in the child tag in xml using python 3

I am trying to add the attributes inside a tag but it should be at the beginning. My input is say:

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

I need an output as:

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

But I am getting this:

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

I used from lxml import etree as ET in my code, but it adds the attribute at the end in the output file. I need at the beginning. The import xml.etree.ElementTree as ET gives the output but in alphabetical order. So I tried lxml module.

My code:

#import xml.etree.ElementTree as ET    
from lxml import etree as ET

tree = ET.parse('sample.xml')
root = tree.getroot()    
for test in root.iter('Test'):
    test.set('Class', 'Hello')

tree.write('output.xml')

Thanks!

Upvotes: 0

Views: 506

Answers (1)

Michael Kay
Michael Kay

Reputation: 163322

The attributes in an element are an unordered set of (name, value) pairs. There's no way to insert an item at a specific position in an unordered set.

If you're generating data for a consuming application that requires the attributes in a particular order, then the consuming application is broken and should be fixed. If you can't fix it, you might be able to find tools that allow you to reorder attributes during serialization: for example Saxon-(PE/EE) has a serialization property saxon:attribute-order.

Upvotes: 1

Related Questions