使用python合并类似的xml文件
我正在尝试使用python合并两个类似的xml文件 file1.xml:使用python合并类似的xml文件,python,xml,Python,Xml,我正在尝试使用python合并两个类似的xml文件 file1.xml: <data> <a> <b> <c>value1</c> <d>value2</d> </b> <e> <f>value3</f> <g>value4</g> </e>
<data>
<a>
<b>
<c>value1</c>
<d>value2</d>
</b>
<e>
<f>value3</f>
<g>value4</g>
</e>
</a>
</data>
价值1
价值2
价值3
价值4
file2.xml
<data>
<a>
<b>
<c>value5</c>
<d>value6</d>
</b>
<e>
<f>value7</f>
<g>value8</g>
</e>
</a>
</data>
价值5
价值6
价值7
价值8
所需的输出(file3.xml)。合并重复b元素的所有子元素,但不合并重复e元素
<data>
<a>
<b>
<c>value1</c>
<d>value2</d>
<c>value5</c>
<d>value6</d>
</b>
<e>
<f>value3</f>
<g>value4</g>
</e>
<e>
<f>value7</f>
<g>value8</g>
</e>
</a>
</data>
价值1
价值2
价值5
价值6
价值3
价值4
价值7
价值8
为了解决您的问题,我将XML转换为Python dict并手动合并字典。在我将dict重新转换为XML之后。类似于此(使用Python 2.7测试):
我对转换部分使用
xmltodict
模块。要安装它,请使用pip安装xmltodict
欢迎使用!与其他论坛不同,Stack Overflow是一个问答网站。读者,比如你自己,会提出问题,而其他读者会试图回答。你的帖子缺少一个成功帖子的基本要素:一个问题!你的问题到底是什么?谢谢你的回答。这是工作,但不完全是我想要的结果。例如,这是合并所有重复的元素。我不想像上面所需的输出文件那样合并元素“e”。是的,我知道,但这很难,因为我没有不合并所有重复元素的标准。如何知道可以合并(b
)或不合并(e
)的元素?
import xmltodict
import collections
def merge_dict(d, u):
"""
Merge two dictionaries. Manage nested dictionary and multiple values with same key.
Return merged dict
"""
for k, v in u.items():
if isinstance(v, collections.Mapping):
d[k] = merge_dict(d.get(k, {}), v)
else:
# No more nested
if k in d:
# Manage multiple values with same name
if not isinstance(d[k], list):
# if not a list create one
d[k] = [d[k]]
d[k].append(v)
else:
# Single value
d[k] = v
return d
if __name__ == "__main__":
# Open input files
with open("file1.xml", "r") as file1_xml, open("file2.xml", "r") as file2_xml:
# Convert xml to dictionary
file1_dict = xmltodict.parse(file1_xml.read())
file2_dict = xmltodict.parse(file2_xml.read())
# Merge dictionaries with special function
file3_dict = merge_dict(file1_dict, file2_dict)
# Open output file
with open("file3.xml", "w") as file3_xml:
file3_xml.write(xmltodict.unparse(file3_dict))