2015-10-25 66 views
-1

我想比較兩個格式相似的xml文件。兩行xml文件逐行比較

f1.xml

<apple name="a" mb="15" lb="0" write="true" value="1"/> 
<apple name="b" mb="31" lb="16" write="true" value="2"/> 
<apple name="c" mb="32" lb="32" write="true" value="3"/> 

f2.xml

<apple name="a" mb="15" lb="0" write="true" value="1"/> 
<apple name="b" mb="31" lb="16" write="true" value="3"/> 
<apple name="c" mb="32" lb="32" write="true" value="2"/> 

我謹行比較線並打印出值是否爲同蘋果的名字不同。

我該怎麼用Python做到這一點?

回答

1

首先,你需要通過給它一個根元素來使你的xml有效的xml。

然後使用lxml來解析它。

然後使用您喜歡的任何函數進行比較。

這個例子不是最簡單的方法,但它確實將它分解成許多可以使用的不同功能。

from lxml import etree 

def dem_apples(xml1,xml2,join_on='name'): 

    tree1 = etree.fromstring(xml1) 
    tree2 = etree.fromstring(xml2) 

    for a1 in tree1.xpath('./apple'): 
     a1_attr_set = set(dict(a1.attrib).items()) 
     a2_list = tree2.xpath('./apple[@{0}="{1}"]'.\ 
     format(join_on,a1.get(join_on))) 
     for a2 in a2_list: 
      a2_attr_set = set(dict(a2.attrib).items()) 
      diff = a1_attr_set - a2_attr_set 
      if diff: 

       print(a1.get(join_on),diff,a2_attr_set-a1_attr_set) 

if __name__ == '__main__': 

    xml_string1=""" 
    <fruit> 
    <apple name="a" mb="15" lb="0" write="true" value="1"/> 
    <apple name="b" mb="31" lb="16" write="true" value="2"/> 
    <apple name="c" mb="32" lb="32" write="true" value="3"/> 
    </fruit> 
    """ 

    xml_string2=""" 
    <fruit> 
    <apple name="a" mb="15" lb="0" write="true" value="1"/> 
    <apple name="b" mb="31" lb="16" write="true" value="3"/> 
    <apple name="c" mb="32" lb="32" write="true" value="2"/> 
    </fruit> 
    """ 
    dem_apples(xml_string1,xml_string2)