如何使用 python 将大量 XML 插入到另一个 XML 文件中?

How to insert a large amount of XML into another XML file using python?

这与这个问题非常相似:,但我需要能够将许多具有许多属性的不同 xml 文档插入现有 XML 的深层嵌套部分子元素具有相同名称的文档。这是一个没有属性的 MWE 使事情变得混乱

我需要插入元素的主文档:

<a><b1><array><c1></c1><c1></c1><c1></c1></array></b1><b2></b2></a>

我要插入的XML:

<f><g><h2></h2><h1></h1></g></f>

我想要的输出:

<a>
   <b1>
      <array>
         <c1 />
         <c1>
            <f>
               <g>
                  <h2 />
                  <h1 />
               </g>
            </f>
         </c1>
         <c1 />
      </array>
   </b1>
   <b2 />
</a>

我当前的python代码:

import xml.etree.ElementTree as ET 

top_xml = ET.fromstring("<a><b1><array><c1></c1></array></b1><b2></b2></a>")
bottom_xml = ET.fromstring("<f><g><h2></h2><h1></h1></g></f>")

#want to insert `bottom_xml` under the <c1> tag

这是我卡住的地方。 ElementTree.insertElementTree.append 似乎适用于顶部元素。我看到其他答案使用 ElementTree.subelement 将简单的 xml 元素添加到子元素,但是手动重新创建 bottom_xml 的 xml 结构时可能有数百行深似乎很笨拙.

使用find获取要插入的节点:

 top_xml = ET.fromstring("<a><b1><array><c1></c1></array></b1><b2></b2></a>")

 bottom_xml = ET.fromstring("<f><g><h2></h2><h1></h1></g></f>")

 insert_node = top_xml.find('.//c1')

 insert_node.append(bottom_xml)

则结果为:

In [31]: print(ET.tostring(top_xml).decode())
<a><b1><array><c1><f><g><h2 /><h1 /></g></f></c1></array></b1><b2 /></a>

这是有效的,因为使用 find 提取的对象仍然是根对象的一部分,并且您所做的任何更改都会反映回根对象。

已找到有关 xpath 查找支持的表达式的更多信息 here

如果你想要更高级的东西,我建议使用 lxml

编辑

根据你的问题,你想在第二个元素上插入,可以使用[position]

例如:

insert_node = top_xml.find('.//c1[2]')

结果:

In [73]: print(ET.tostring(top_xml).decode())
<a><b1><array><c1 /><c1><f><g><h2 /><h1 /></g></f></c1><c1 /></array></b1><b2 /></a>