我正在尝试使用Python将多个XML文件合并在一起,而不使用外部库。XML文件具有嵌套元素。
示例文件1:
<root>
<element1>textA</element1>
<elements>
<nested1>text now</nested1>
</elements>
</root>
示例文件2:
<root>
<element2>textB</element2>
<elements>
<nested1>text after</nested1>
<nested2>new text</nested2>
</elements>
</root>
我想要的:
<root>
<element1>textA</element1>
<element2>textB</element2>
<elements>
<nested1>text after</nested1>
<nested2>new text</nested2>
</elements>
</root>
我尝试过的:
来自this answer。
from xml.etree import ElementTree as et
def combine_xml(files):
first = None
for filename in files:
data = et.parse(filename).getroot()
if first is None:
first = data
else:
first.extend(data)
if first is not None:
return et.tostring(first)
我得到的:
<root>
<element1>textA</element1>
<elements>
<nested1>text now</nested1>
</elements>
<element2>textB</element2>
<elements>
<nested1>text after</nested1>
<nested2>new text</nested2>
</elements>
</root>
我希望你能理解我的问题。我正在寻找一个合适的解决方案,任何指导都会很好。
为了澄清这个问题,使用我现有的解决方案,嵌套元素不会合并。
您发布的代码所做的是组合所有元素,而不管是否已经存在具有相同标记的元素。因此,您需要遍历这些元素,并以您认为合适的方式手动检查和组合它们,因为这不是处理XML文件的标准方法。我无法比代码更好地解释它,所以这里,或多或少地评论了一下:
谢谢,但我的问题是通过考虑属性来合并。这是我的补丁后的代码:
相关问题 更多 >
编程相关推荐