lxml preserves attributes order?

自闭症网瘾萝莉.ら 提交于 2019-12-24 11:27:47

问题


I was writing my aplication using minidom but minidom does not preserve attribute order(sorts alphabetically), so I decided to do it using lxml.

However in the following lines of code I'm not getting the desired order:

import lxml.etree as ET
SATNS = "link_1"
NS = "link_2"
location_attribute = '{%s}schemaLocation' % NS
root = ET.Element('{%s}Catalogo' % SATNS, nsmap={'catalogocuentas':SATNS}, attrib=
   {location_attribute: 'http://www.sat.gob.mx/catalogocuentas'}, Ano="2014",       Mes="02",   TotalCtas="219", RFC="ALF040329CX6", Version="1.0")
print (ET.tostring(root, pretty_print=True))

This is what I'm expecting to get:

<catalogocuentas:Catalogo xmlns:catalogocuentas="link_1"
xmlns:xsi="link_2" xsi:schemaLocation="http://www.sat.gob.mx/catalogocuentas"
Ano="2014" Mes="02" TotalCtas="219" RFC="XXX010101XXX" Version="1.0">
</catalogocuentas:Catalogo>

Which is in the order that I filled in:

root=ET.element(...)

But I'm getting the next, that has no order:

<catalogocuentas:Catalogo xmlns:catalogocuentas="link_1" 
xmlns:xsi="link_2" RFC="ALF040329CX6" Version="1.0" 
Mes="02" xsi:schemaLocation="http://www.sat.gob.mx/catalogocuentas" Ano="2014" TotalCtas="219">
</catalogocuentas:Catalogo>

Is there a way to fix this problem?

Thanks in advance!!


回答1:


Dictionaries in Python are unordered. Keyword arguments are passed to functions by a dictionary traditionally named **kwargs, and so the order is lost. The function can't possibly know what order the arguments to ET.element came in.

As stated in this question, there isn't really any way to get this done. XML doesn't care about attribute order, so there isn't really any good reason to do it.



来源:https://stackoverflow.com/questions/25518415/lxml-preserves-attributes-order

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