比较两个xml文件而不管它们的顺序

时间:2015-06-29 08:54:25

标签: python xml comparison lxml

我目前正在开发一个python项目,并且遇到了一个与使用python比较两个XML文件相关的小问题。现在假设我们有两个xml文件:

文件:

<m1:time timeinterval="5">
   <m1:vehicle distance="40" speed="5"\>

   <m1:location hours = "1" path = '1'\>
      <m1:feature color="2" type="a">564</m1:feature>
      <m1:feature color="3" type="b">570</m1:feature>
      <m1:feature color="4" type="c">570</m1:feature>
   <\m1:location>

   <m1:location hours = "5" path = '1'\>
      <m1:feature color="6" type="a">560</m1:feature>
      <m1:feature color="7" type="b">570</m1:feature>
      <m1:feature color="8" type="c">580</m1:feature>   
   <\m1:location>

   <m1:location hours = "9" path = '1'\>
      <m1:feature color="10" type="a">560</m1:feature>
      <m1:feature color="11" type="b">570</m1:feature>
      <m1:feature color="12" type="c">580</m1:feature>   
   <\m1:location>
</m1:time>

B档:

<m1:time timeinterval="6">
   <m1:vehicle distance="40" speed="5"\>

   <m1:location hours = "5" path = '1'\>
      <m1:feature color="6" type="a">560</m1:feature>
      <m1:feature color="7" type="b">570</m1:feature>
      <m1:feature color="8" type="c">580</m1:feature>   
   <\m1:location>

   <m1:location hours = "1" path = '1'\>
      <m1:feature color="2" type="a">564</m1:feature>
      <m1:feature color="3" type="b">570</m1:feature>
      <m1:feature color="4" type="c">570</m1:feature>
   <\m1:location>

   <m1:location hours = "9" path = '1'\>
      <m1:feature color="10" type="a">560</m1:feature>
      <m1:feature color="11" type="b">570</m1:feature>
      <m1:feature color="12" type="c">580</m1:feature>   
   <\m1:location>

</m1:time>
  • 我想问的是如何将A文件与B文件进行比较 确保通过&#34; location&#34;的顺序元素是不同的 在这两个文件中,仍然使用python显示相同的内容?
  • 我尝试了各种方法,并试图参考 this问题,但在这个项目中,我想开发一个 我自己的方法,我不能使用任何已有的工具。

到目前为止,我尝试过的方法是:

我正在使用LXML,我从A文件中获取子项的各个属性并将它们存储在列表中。然后我将B文件的元素和子属性与存储在该列表中的值进行比较。

首先,这种方法不起作用,我也无法想到完成此任务的任何有效程序。你们能否对此有所了解?

谢谢。

1 个答案:

答案 0 :(得分:1)

听起来你需要一些XML解析器。 我的第一个建议是使用DOM解析器(或者自己创建一个非常基本的解析器)。通过读取两个XML文件然后比较树,您可以轻松验证它们是否相同。

但这不是很有效。读取第二个XML文件时可以进行验证。然而,您必须删除匹配的元素。 (为了确保没有留下不匹配的元素)

但我很好奇为什么你的列表方法不起作用。你能提供更多相关信息吗?

相关问题