我有两个包含大量项目的大型XML文件(c.100MB)。我想输出他们之间的差异。Python比较XML文件
每个项目都有一个ID,我需要检查它是否在两个文件中。如果是,那么我需要比较该物品的各个值,以确定它是同一物品。
SAX解析器是解决这个问题的最好方法,它是如何使用的?我使用了元素树,并找到了哪些工作在较小的文件上,但现在我无法处理大文件。
srcTree = ElementTree()
srcTree.parse(srcFile)
# finds all the items in both files
srcComponents = (srcTree.find('source')).find('items')
srcItems = srcComponents.findall('item')
dstComponents = (dstTree.find('source')).find('items')
dstItems = dstComponents.findall('item')
# parses the source file to find the values of various fields of each
# item and adds the information to the source set
for item in srcItems:
srcId = item.get('id')
srcList = [srcId]
details = item.find('values')
srcVariables = details.findall('value')
for var in srcVariables:
srcList.append((var.get('name'),var.text))
srcList = tuple(srcList)
srcSet.add(srcList)
向我们展示你写 – wroniasty 2012-07-30 10:51:58
失败的代码它将所有内容加载到内存中,因此它不适用于这些文件。我使用元素树来获取每个xml文件中的数据树。我在树上使用find来获取所有项目到列表中。然后,我循环这些项目以获取每个项目的值并将信息存储在一组元组中:[(id,val,val),(id,val,val)]。我为这两个文件做了这个。找到这些集合的差异,然后将结果存储在一个文件中。 – charlie123 2012-07-30 10:59:32