<h2>属性的有序化</h2>
<p>从lxml 3.3.3开始(可能也在早期版本中),您可以将属性的<a href="http://docs.python.org/2/library/collections.html#collections.OrderedDict">OrderedDict</a>传递给<code>lxml.etree.(Sub)Element</code>构造函数,使用<code>lxml.etree.tostring(root)</code>时将保留顺序:</p>
<pre><code>sig.fileformat = etree.SubElement(sig.fileformats, "FileFormat", OrderedDict([("ID",str(db.ID)), ("Name",db.name), ("PUID","fileSig/{}".format(str(db.ID))), ("Version",""), ("MIMEType","")]))
</code></pre>
<p>注意,ElementTree API(<code>xml.etree.ElementTree</code>)不会保留属性顺序,即使您向<code>xml.etree.ElementTree.(Sub)Element</code>构造函数提供了<code>OrderedDict</code>!</p>
<p>更新:还请注意,使用<code>lxml.etree.(Sub)Element</code>构造函数的<code>**extra</code>参数指定属性并不会保留属性顺序:</p>
<pre><code>>>> from lxml.etree import Element, tostring
>>> from collections import OrderedDict
>>> root = Element("root", OrderedDict([("b","1"),("a","2")])) # attrib parameter
>>> tostring(root)
b'<root b="1" a="2"/>' # preserved
>>> root = Element("root", b="1", a="2") # **extra parameter
>>> tostring(root)
b'<root a="2" b="1"/>' # not preserved
</code></pre>