Elementtree setting attribute order

不羁的心 提交于 2019-11-30 21:21:09

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!