我正在尝试合并两个xml文件。这些文件包含相同的总体结构,但细节不同。
文件1.xml:
<book>
<chapter id="113">
<sentence id="1">
<word id="128160">
<POS Tag="V"/>
<grammar type="STEM"/>
<Aspect type="IMPV"/>
<Number type="S"/>
</word>
<word id="128161">
<POS Tag="V"/>
<grammar type="STEM"/>
<Aspect type="IMPF"/>
</word>
</sentence>
<sentence id="2">
<word id="128162">
<POS Tag="P"/>
<grammar type="PREFIX"/>
<Tag Tag="bi+"/>
</word>
</sentence>
</chapter>
</book>
文件2.xml:
<book>
<chapter id="113">
<sentence id="1">
<word id="128160">
<concept English="joke"/>
</word>
<word id="128161">
<concept English="romance"/>
</word>
</sentence>
<sentence id="2">
<word id="128162">
<concept English="happiness"/>
</word>
</sentence>
</chapter>
</book>
所需输出为:
<book>
<chapter id="113">
<sentence id="1">
<word id="128160">
<concept English="joke"/>
<POS Tag="V"/>
<grammar type="STEM"/>
<Aspect type="IMPV"/>
<Number type="S"/>
</word>
<word id="128161">
<concept English="romance"/>
<POS Tag="V"/>
<grammar type="STEM"/>
<Aspect type="IMPF"/>
</word>
</sentence>
<sentence id="2">
<word id="128162">
<concept English="happiness"/>
<POS Tag="P"/>
<grammar type="PREFIX"/>
<Tag Tag="bi+"/>
</word>
</sentence>
</chapter>
</book>
好吧,我试着在path中这样做,但没有得到所需的输出:
import os, os.path, sys
import glob
from xml.etree import ElementTree
output = open('merge.xml','w')
files="sample"
xml_files = glob.glob(files +"/*.xml")
xml_element_tree = None
for xml_file in xml_files:
data = ElementTree.parse(xml_file).getroot()
# print ElementTree.tostring(data)
for word in data.iter('word'):
if xml_element_tree is None:
xml_element_tree = data
insertion_point = xml_element_tree.findall("book/chapter/sentence/word/*")
else:
insertion_point.extend(word)
if xml_element_tree is not None:
print>>output, ElementTree.tostring(xml_element_tree)
拜托,有什么帮助吗
我以前做过类似事情的一种方法是创建一个xml文档,然后附加您要查找的值。我不相信有办法把他们“合并”
这是一个解决方案。从一个空的合并文档开始,然后在枚举文件时,将找不到的元素添加到合并文档中。你可以概括这一点,但这是第一步:
如果希望将File2合并到File1中,则可以循环遍历File2中的所有元素,然后将属性从File2的元素复制到File1的元素中。
在我正在做的一个项目中,我必须做类似的事情。这是我目前的解决方案,应该在Python2.7下工作。
注意,我进一步添加了在公共节点之间复制属性的需求。您将看到我将以下属性添加到:
然后我又加了一句:
最后合并的文件中有三名权力三人组成员。
我还添加了
<sentance id='3'/>
来证明元素的顺序不再重要。这将产生以下输出:
相关问题 更多 >
编程相关推荐