python lxml模块对xml属性顺序进行排列_python-lxml:强制执行属性的特定顺序

I have an XML writing script that outputs XML for a specific 3rd party tool.

I've used the original XML as a template to make sure that I'm building all the correct elements, but the final XML does not appear like the original.

I write the attributes in the same order, but lxml is writing them in its own order.

I'm not sure, but I suspect that the 3rd part tool expects attributes to appear in a specific order, and I'd like to resolve this issue so I can see if its the attrib order that making it fail, or something else.

Source element:

My source script:

sig.fileformat = etree.SubElement(sig.fileformats, "FileFormat", ID = str(db.ID), Name = db.name, PUID="fileSig/{}".format(str(db.ID)), Version = "", MIMEType = "")

My resultant XML:

Is there a way of constraining the order they are written?

解决方案

Attribute ordering and readability

As the commenters have mentioned, attribute order has no semantic significance in XML, which is to say it doesn't change the meaning of an element:

There is an analogous characteristic in SQL, where column order doesn't change

the meaning of a table definition. XML attributes and SQL columns are a set

(not an ordered set), and so all that can "officially" be said about either

one of those is whether the attribute or column is present in the set.

That said, it definitely makes a difference to human readability which order

these things appear in and in situations where constructs like this are authored and appear in text (e.g. source code) and must be interpreted, a careful ordering makes a lot of sense to me.

Typical parser behavior

Any XML parser that treated attribute order as significant would be out of compliance with the XML standard. That doesn't mean it can't happen, but in my experience it is certainly unusual. Still, depending on the provenence of the tool you mention, it's a possibility that may be worth testing.

As far as I know, lxml has no mechanism for specifying the order attributes appear in serialized XML, and I would be surprised if it did.

In order to test the behavior I'd be strongly inclined to just write a text-based template to generate enough XML to test it out:

id = 1

name = 'Development Signature'

puid = 'dev/1'

version = '1.0'

mimetype = 'text/x-test-signature'

template = ('

'MIMEType="%s">')

xml = template % (id, name, puid, version, mimetype)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值