逐行比较两个xml文件

时间:2015-10-25 12:28:46

标签: python xml compare

我想比较两个格式相似的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 个答案:

答案 0 :(得分:1)

首先,你需要通过给它一个根元素来使你的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)
相关问题