gpt4 book ai didi

python - 比较两个 xml 文件,无论其顺序如何

转载 作者:太空宇宙 更新时间:2023-11-03 17:36:46 34 4
gpt4 key购买 nike

我目前正在开发一个 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文件确保“location”元素的顺序不同在这两个文件中,使用 python 仍然显示相同的内容?
  • 我尝试过各种方法,也尝试引用 this问题,但在这个项目中我想开发一个我自己的方法,我无法使用任何现有的工具。

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

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

首先,这种方法不起作用,我也无法想出任何有效的程序来完成这项任务。你们能解释一下吗?

谢谢。

最佳答案

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

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

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

关于python - 比较两个 xml 文件,无论其顺序如何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31111496/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com