在Python中比较两个XML文件

15 投票
4 回答
63464 浏览
提问于 2025-04-18 11:35

我刚开始学习用Python编程,遇到了一些理解上的问题。我想比较两个XML文件,这两个文件都挺大的。下面是我想比较的文件类型的例子。

xmlfile1:

<xml>
    <property1>
          <property2>    
               <property3>

               </property3>
          </property2>    
    </property1>    
</xml>

xml file2:

<xml>
    <property1>
        <property2>    
            <property3> 
                <property4>

                </property4>    
            </property3>
        </property2>    
    </property1>

</xml>

我提到的property1和property2跟文件里实际的内容不一样。XML文件里有很多属性。我想把这两个XML文件进行比较。

我正在使用lxml这个解析器,想要比较这两个文件,并打印出它们之间的不同之处。

但我不知道怎么自动解析和比较它们。

我试着阅读lxml解析器的文档,但还是不明白怎么用它来解决我的问题。

有没有人能告诉我该如何处理这个问题呢?

代码示例会很有帮助。

还有一个问题,我这样做是否正确?我是不是漏掉了什么?如果你知道其他相关的概念,请告诉我。

4 个回答

1

这是另一个使用 xml.etree 的脚本。虽然它很糟糕,但确实能用 :)

#!/usr/bin/env python

import sys
import xml.etree.ElementTree as ET

from termcolor import colored

tree1 = ET.parse(sys.argv[1])
root1 = tree1.getroot()

tree2 = ET.parse(sys.argv[2])
root2 = tree2.getroot()

class Element:
    def __init__(self,e):
        self.name = e.tag
        self.subs = {}
        self.atts = {}
        for child in e:
            self.subs[child.tag] = Element(child)

        for att in e.attrib.keys():
            self.atts[att] = e.attrib[att]

        print "name: %s, len(subs) = %d, len(atts) = %d" % ( self.name, len(self.subs), len(self.atts) )

    def compare(self,el):
        if self.name!=el.name:
            raise RuntimeError("Two names are not the same")
        print "----------------------------------------------------------------"
        print self.name
        print "----------------------------------------------------------------"
        for att in self.atts.keys():
            v1 = self.atts[att]
            if att not in el.atts.keys():
                v2 = '[NA]'
                color = 'yellow'
            else:
                v2 = el.atts[att]
                if v2==v1:
                    color = 'green'
                else:
                    color = 'red'
            print colored("first:\t%s = %s" % ( att, v1 ), color)
            print colored("second:\t%s = %s" % ( att, v2 ), color)

        for subName in self.subs.keys():
            if subName not in el.subs.keys():
                print colored("first:\thas got %s" % ( subName), 'purple')
                print colored("second:\thasn't got %s" % ( subName), 'purple')
            else:
                self.subs[subName].compare( el.subs[subName] )



e1 = Element(root1)
e2 = Element(root2)

e1.compare(e2)
6

如果你想比较XML的内容和属性,而不仅仅是逐字节比较文件,那么这个问题就有些复杂了,所以没有一种解决方案适合所有情况。

你需要了解XML文件中哪些内容是重要的。

一般来说,元素标签中属性的顺序通常不应该影响比较结果。也就是说,两个XML文件如果只是属性的顺序不同,通常应该被认为是相同的。

但这只是一般情况。

具体的情况会依赖于应用。例如,文件中某些元素的空格格式可能不重要,空格可能是为了让XML更易读而添加的,等等。

最近版本的ElementTree模块有一个叫canonicalize()的函数,可以处理一些简单的情况,把XML字符串转换成标准格式。

我在最近一个项目的单元测试中使用了这个函数,用来比较一个已知的XML输出和一个有时会改变属性顺序的包的输出。在这种情况下,文本元素中的空格并不重要,但有时会用于格式化。

import xml.etree.ElementTree as ET
def _canonicalize_XML( xml_str ):
    """ Canonicalizes XML strings, so they are safe to 
        compare directly. 
        Strips white space from text content."""

    if not hasattr( ET, "canonicalize" ):
        raise Exception( "ElementTree missing canonicalize()" )

    root = ET.fromstring( xml_str )
    rootstr = ET.tostring( root )
    return ET.canonicalize( rootstr, strip_text=True )

使用方法大概是这样的:

file1 = ET.parse('file1.xml')
file2 = ET.parse('file2.xml')

canon1 = _canonicalize_XML( ET.tostring( file1.getroot() ) )
canon2 = _canonicalize_XML( ET.tostring( file2.getroot() ) )

print( canon1 == canon2 )

在我的版本中,Python 2没有canonicalize()这个函数,但Python 3有。

7

我解决这个问题的方法是把每个XML文件转换成一个叫做 xml.etree.ElementTree 的东西,然后逐层遍历它们。我还加入了一个功能,可以在比较的时候忽略一些特定的属性。

第一段代码是用来定义这个类的:

import xml.etree.ElementTree as ET
import logging

class XmlTree():

    def __init__(self):
        self.hdlr = logging.FileHandler('xml-comparison.log')
        self.formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')

    @staticmethod
    def convert_string_to_tree( xmlString):

        return ET.fromstring(xmlString)

    def xml_compare(self, x1, x2, excludes=[]):
        """
        Compares two xml etrees
        :param x1: the first tree
        :param x2: the second tree
        :param excludes: list of string of attributes to exclude from comparison
        :return:
            True if both files match
        """

        if x1.tag != x2.tag:
            self.logger.debug('Tags do not match: %s and %s' % (x1.tag, x2.tag))
            return False
        for name, value in x1.attrib.items():
            if not name in excludes:
                if x2.attrib.get(name) != value:
                    self.logger.debug('Attributes do not match: %s=%r, %s=%r'
                                 % (name, value, name, x2.attrib.get(name)))
                    return False
        for name in x2.attrib.keys():
            if not name in excludes:
                if name not in x1.attrib:
                    self.logger.debug('x2 has an attribute x1 is missing: %s'
                                 % name)
                    return False
        if not self.text_compare(x1.text, x2.text):
            self.logger.debug('text: %r != %r' % (x1.text, x2.text))
            return False
        if not self.text_compare(x1.tail, x2.tail):
            self.logger.debug('tail: %r != %r' % (x1.tail, x2.tail))
            return False
        cl1 = x1.getchildren()
        cl2 = x2.getchildren()
        if len(cl1) != len(cl2):
            self.logger.debug('children length differs, %i != %i'
                         % (len(cl1), len(cl2)))
            return False
        i = 0
        for c1, c2 in zip(cl1, cl2):
            i += 1
            if not c1.tag in excludes:
                if not self.xml_compare(c1, c2, excludes):
                    self.logger.debug('children %i do not match: %s'
                                 % (i, c1.tag))
                    return False
        return True

    def text_compare(self, t1, t2):
        """
        Compare two text strings
        :param t1: text one
        :param t2: text two
        :return:
            True if a match
        """
        if not t1 and not t2:
            return True
        if t1 == '*' or t2 == '*':
            return True
        return (t1 or '').strip() == (t2 or '').strip()

第二段代码包含了一些XML示例和它们的比较:

xml1 = "<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>"

xml2 = "<note><to>Tove</to><from>Daniel</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>"

tree1 = XmlTree.convert_string_to_tree(xml1)
tree2 = XmlTree.convert_string_to_tree(xml2)

comparator = XmlTree()

if comparator.xml_compare(tree1, tree2, ["from"]):
    print "XMLs match"
else:
    print "XMLs don't match"

这段代码的大部分功劳要归功于 syawar

12

这个问题其实挺有挑战性的,因为“差异”这个词的意思往往因人而异。在这里,有些信息在语义上是“等价”的,但你可能并不想把它们标记为差异。

你可以试试使用 xmldiff,这个工具是基于一篇论文的研究,论文的标题是 层次结构信息中的变化检测

撰写回答