如何在特定级别合并两个xml文件

问题描述 投票:0回答:1

我想使用Python合并两个xml文件:

文件1.xml

<?xml version='1.0' encoding='ASCII'?>
<MyData>
  <Elements>
    <Element>
      <ElementID>15</ElementID>
    </Element>
  </Elements>
</MyData>

File2.xml

<?xml version='1.0' encoding='ASCII'?>
<MyData>
  <Elements>
    <Element>
      <ElementID>16</ElementID>
    </Element>
  </Elements>
</MyData>

我可以使用这篇Medium post中建议的方法:

import xml.etree.ElementTree as ET
tree1 = ET.parse('File1.xml')
tree2 = ET.parse('File2.xml')
root1 = tree1.getroot()
root2 = tree2.getroot()
root1.extend(root2)
tree1.write('merged_files.xml')

返回:

<MyData>
  <Elements>
    <Element>
      <ElementID>15</ElementID>
    </Element>
  </Elements>
<Elements>
    <Element>
      <ElementID>16</ElementID>
    </Element>
  </Elements>
</MyData>

但是如何在给定的“级别”合并文件,例如元素?

我想获得:

<MyData>
  <Elements>
    <Element>
      <ElementID>15</ElementID>
    </Element>
    <Element>
      <ElementID>16</ElementID>
    </Element>
  </Elements>
</MyData>
python xml merge elementtree
1个回答
0
投票

我找到了一种方法,可以查找第一个 xml 的 Elements 标签,并将第二个 xml Elements 的数据的所有子级附加到其中

import xml.etree.ElementTree as ET

first_tree = ET.parse('File1.xml')
first_root = first_tree.getroot()

second_tree = ET.parse('File2.xml')
second_root = second_tree.getroot()

first_elements = first_root.find('Elements')
second_elements = second_root.find('Elements')

"""Merges the 'Elements' nodes from two XML files into a single XML file. 
   This code iterates through the 'Elements' 
   nodes in the second XML file and appends them to the 'Elements' in 
   the first XML file. It then writes the merged 
   XML tree to a new file named 'MergedFile.xml'."""
for elem in second_elements:
first_elements.append(elem)

first_tree.write('MergedFile.xml', encoding='ASCII', 
xml_declaration=True)

merged_tree = ET.ElementTree(first_root)
ET.dump(merged_tree)

希望这会有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.