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!