I am trying to create a xml file using lxml, I am well aware that the order of attributes in xml doesn't matter but still I am searching for a method to prevent the attributes in a specific order.
I also tried minidom and that didn't workout too.
In lxml I have the following code:
from lxml import etree as ET
from collections import OrderedDict
root = ET.Element("Root", OrderedDict([("id","0"),("start","0"),("end","200")]))
ET.tostring(root)
This part gives the following ouput with the attributes in the order I wanted since I used OrderedDict here:
<Root id="0" start="0" end="200"/>
Then I created a Child using the same method:
child1 = ET.Element("sentence", OrderedDict([("id","0"),("start","0"),("end","255")]))
root.append(child1)
xml_str = ET.tostring(root, pretty_print=True)
print(xml_str)
Printing the xml_str gives output as I expect:
<Root id="0" start="0" end="200">\n <sentence id="0" start="0" end="255"/>\n</Root>
But when it comes to writing it down to a xml file:
with open('op.xml', 'wb') as f:
f.write(xml_str)
The ouput isn't same when written to op.xml file:
<?xml version="1.0"?>
<Root end="200" start="0" id="0">
<sentence end="255" start="0" id="0"/>
</Root>
Clearly seen that the attributes order have changed, is there any way I can get the ouput as I expect i.e attribute orders being maintained.
I have tried using minidom too, but there also it didn't work even after referring to: Preserve order of attributes when modifying with minidom