比較字符串並不總是奏效。對於考慮兩個等效節點,屬性的順序應該不重要。但是,如果您進行字符串比較,則順序顯然很重要。
我不知道,如果這是一個問題或一個功能,但我lxml.etree的版本保留屬性的順序,如果他們是從文件或字符串解析:
>>> from lxml import etree
>>> h1 = etree.XML('<hat color="blue" price="39.90"/>')
>>> h2 = etree.XML('<hat price="39.90" color="blue"/>')
>>> etree.tostring(h1) == etree.tostring(h2)
False
這可能是版本依賴的(我在Ubuntu上使用Python 2.7.3和lxml.etree 2.3.2);我記得當我想要時(出於可讀性的原因),我無法在一年前找到控制屬性順序的方法。
由於我需要比較不同序列化器產生的XML文件,除了遞歸比較每個節點的標籤,文本,屬性和子元素之外,我沒有其他辦法。當然還有尾巴,如果有什麼有趣的。 LXML和xml.etree.ElementTree
真相的
對比的是,它可能是依賴於實現的。顯然,lxml使用有序的字典或類似的東西,標準的xml.etree。ElementTree的不保留屬性的順序:(是的,換行失蹤,但它是一個小問題。)
Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from lxml import etree
>>> h1 = etree.XML('<hat color="blue" price="39.90"/>')
>>> h2 = etree.XML('<hat price="39.90" color="blue"/>')
>>> etree.tostring(h1) == etree.tostring(h2)
False
>>> etree.tostring(h1)
'<hat color="blue" price="39.90"/>'
>>> etree.tostring(h2)
'<hat price="39.90" color="blue"/>'
>>> etree.dump(h1)
<hat color="blue" price="39.90"/>>>> etree.dump(h2)
<hat price="39.90" color="blue"/>>>>
>>> import xml.etree.ElementTree as ET
>>> h1 = ET.XML('<hat color="blue" price="39.90"/>')
>>> h1
<Element 'hat' at 0x2858978>
>>> h2 = ET.XML('<hat price="39.90" color="blue"/>')
>>> ET.dump(h1)
<hat color="blue" price="39.90" />
>>> ET.dump(h2)
<hat color="blue" price="39.90" />
>>> ET.tostring(h1) == ET.tostring(h2)
True
>>> ET.dump(h1) == ET.dump(h2)
<hat color="blue" price="39.90" />
<hat color="blue" price="39.90" />
True
另一個問題可能是那些被認爲不重要煥比較。例如,某些片段可能包含多餘的空格,我們不想關心。這樣,編寫一些完全符合我們需要的序列化函數總是更好。
一個比較兩個元素的功能可參見[伊塔馬爾的答案](http://stackoverflow.com/a/24349916/2371522)以下。 – One