Elementtree Setting Attribute Order
I am trying to write a python script to standardise generic XML files, used to configure websites and website forms. However to do this I would like to either maintain the original
Solution 1:
Apply monkey patch as mentioned below::
in ElementTree.py
file, there is a function named as _serialize_xml
;
in this function; apply the below mentioned patch;
##for k, v in sorted(items): # remove the sorted here
for k, v in items:
if isinstance(k, QName):
k = k.text
if isinstance(v, QName):
v = qnames[v.text]
else:
v = _escape_attrib(v, encoding)
write(" %s=\"%s\"" % (qnames[k], v))
here; remove the sorted(items)
and make it just items
like i have done above.
Also to disable sorting based on namespace(because in above patch; sorting is still present when namespace is present for xml attribute; otherwise if namespace is not present; then above is working fine); so to do that, replace all {}
with collections.OrderedDict()
from ElementTree.py
Now you have all attributes in a order as you have added them to that xml element.
Before doing all of above; read the copyright message by Fredrik Lundh that is present in ElementTree.py
Post a Comment for "Elementtree Setting Attribute Order"