使用python进行xml比较

使用python进行xml比较,python,xml,lxml,Python,Xml,Lxml,我试图在下面比较python中的两种xml格式,希望您能对我的方法有所帮助 文件1: <p1:car> <p1:feature car="111" type="color">511</p1:feature> <p1:feature car="223" type="color">542</p1:feature> <p1:feature car="299"

我试图在下面比较python中的两种xml格式,希望您能对我的方法有所帮助

文件1:

<p1:car>                           
    <p1:feature car="111" type="color">511</p1:feature>
    <p1:feature car="223" type="color">542</p1:feature>
    <p1:feature car="299" type="color">559</p1:feature>
    <p1:feature car="323" type="color">564</p1:feature>
    <p1:feature car="353" type="color">564</p1:feature>
    <p1:feature car="391" type="color">570</p1:feature>
    <p1:feature car="448" type="color">570</p1:feature>

    <p1:feature car="111" type="tires" unit="percent">511</p1:feature>
    <p1:feature car="223" type="tires" unit="percent">513</p1:feature>
    <p1:feature car="299" type="tires" unit="percent">516</p1:feature>
    <p1:feature car="323" type="tires" unit="percent">516</p1:feature>
    <p1:feature car="353" type="tires" unit="percent">518</p1:feature>
    <p1:feature car="391" type="tires" unit="percent">520</p1:feature>
    <p1:feature car="448" type="tires" unit="percent">520</p1:feature>
</p1:car>
另外,你可以给我建议一些想法和不同的方法。我被这个问题困扰了很长时间,我想马上解决这个问题

我的尝试:

我使用lxml进行比较工作,并尝试以以下方式使用for循环:

for i,j in zip(file1.getchildren(),file2.getchildren()):
        if (int(i.get("car")) & int(i.text)) != (int(j.get("car")) & int(j.text)):
               print "difference of both files"

由于行对行的比较方法,我从两个文件的第二段开始得到了所有错误的结果,因为第二个文件缺少一行

我想你想要的是
difflib
。请看一下官方文件

一般来说,您想要的是:

from difflib import Differ
text_1 = file_1.read() # getting XML contents
text_2 = file_2.read() # getting XML contents from second file
d = Differ()
result = d.compare(text_1, text_2)

有关用法的更多详细信息,请参阅官方文档。

谢谢您的输入。我们可以使用difflib来比较xml文件的各个部分吗?如果不是整个文档。因为我的xml文件的结构非常复杂complex@DhruvJ如果您想深入研究这个XML比较问题,我建议您为此使用第三方库,例如
xmldiff
(可通过pip获得)或
formencode
(可从BitBucket获得)。关于第二个图书馆,也有类似的讨论。-梅内加佐,我会研究一下。谢谢您的建议。这可能值得一试:
for i,j in zip(file1.getchildren(),file2.getchildren()):
        if (int(i.get("car")) & int(i.text)) != (int(j.get("car")) & int(j.text)):
               print "difference of both files"
from difflib import Differ
text_1 = file_1.read() # getting XML contents
text_2 = file_2.read() # getting XML contents from second file
d = Differ()
result = d.compare(text_1, text_2)