我想比较这两个xml文件:
File1.xml:
<ngs_sample id="40332">
<workflow value="salmonella" version="101_provisional" />
<results>
<gastro_prelim_st reason="not novel" success="false">
<type st="1364" />
<type st="9999" />
</gastro_prelim_st>
</results>
</ngs_sample>
File2.xml:
<ngs_sample id="40332">
<workflow value="salmonella" version="101_provisional" />
<results>
<gastro_prelim_st reason="not novel" success="false">
<type st="1364" />
</gastro_prelim_st>
</results>
</ngs_sample>
我已经使用xmldiff
来比较a.xml和b.xml:
def compare_xmls(observed,expected):
from xmldiff import main, formatting
formatter = formatting.DiffFormatter()
diff = main.diff_files(observed,expected,formatter=formatter)
return diff
out = compare_xmls(a.xml, b.xml)
print(out)
输出:
[delete, /ngs_sample/results/gastro_prelim_st/type[2]]
任何人都知道如何识别两个xml文件之间的区别,即与文件b.xml相比已经删除了什么。任何人都建议以其他方式比较python中的xml文件吗?
答案 0 :(得分:2)
您可以切换到XMLFormatter
并手动过滤出结果:
...
# Change formatter:
formatter = formatting.XMLFormatter(normalize=formatting.WS_BOTH)
...
# after `out` has been retrieved:
import re
for i in out.splitlines():
if re.search(r'\bdiff:\w+', i):
print(i)
# Result:
# <type st="9999" diff:delete=""/>
答案 1 :(得分:0)
使用xmldiff执行此确切任务。
from xmldiff import main
diff = main.diff_files("file1.xml", "file2.xml")
print(diff)
[DeleteNode(node='/ngs_sample/results/gastro_prelim_st/type[2]')]
答案 2 :(得分:0)
另一种选择是使用xml2
https://github.com/clone/xml2(以及类似bash
进程替换的东西)
$ diff --color <(xml2 < File1.xml) <(xml2 < File2.xml)
7,8d6
< /ngs_sample/results/gastro_prelim_st/type
< /ngs_sample/results/gastro_prelim_st/type/@st=9999
答案 3 :(得分:-1)
尝试XmlXdiff,当前仅提供svg输出。但是提供文本输出或接口类应该很简单。
XmlXDiff网站上的一些示例代码:
from XmlXdiff.XReport import DrawXmlDiff
_xml1 = """<root><deleted>with content</deleted><unchanged/><changed name="test1" /></root>"""
_xml2 = """<root><unchanged/><changed name="test2" /><added/></root>"""
with open("test1.xml", "w") as f:
f.write(_xml1)
with open("test2.xml", "w") as f:
f.write(_xml2)
x = DrawXmlDiff("test1.xml", "test2.xml")
x.saveSvg('xdiff.svg')