python lxml模块对xml属性顺序进行排列_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))

This is what I'm expecting to get:

xmlns:xsi="link_2" xsi:schemaLocation="http://www.sat.gob.mx/catalogocuentas"

Ano="2014" Mes="02" TotalCtas="219" RFC="XXX010101XXX" Version="1.0">

Which is in the order that I filled in:

root=ET.element(...)

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

xmlns:xsi="link_2" RFC="ALF040329CX6" Version="1.0"

Mes="02" xsi:schemaLocation="http://www.sat.gob.mx/catalogocuentas" Ano="2014" TotalCtas="219">

Is there a way to fix this problem?

Thanks in advance!!

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值