lxml保留属性顺序吗? [英] lxml preserves attributes order?

查看:92
本文介绍了lxml保留属性顺序吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当时使用minidom来编写应用程序,但是minidom不保留属性顺序(按字母顺序排序),因此我决定使用lxml来实现.

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))

这是我期望得到的:

<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>

按照我填写的顺序:

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?

提前谢谢!

推荐答案

Python中的词典为订单丢失.该函数可能无法知道ET.element的参数按什么顺序输入.

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.

在此问题中所述,真的没有任何方法可以做到这一点. XML不在乎属性顺序,因此确实没有任何很好的理由.

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.

这篇关于lxml保留属性顺序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆