首页 > 解决方案 > 按名称将节点插入到特定级别的 ElementTree 树

问题描述

如果我有一个深度未知的 XML ElementTree,我想将一个节点作为子节点插入到特定的父节点(已知)。我到目前为止的代码(来自其他一些线程)如下:

my_tree.xml

<?xml version="1.0" encoding="UTF-8"?>
<data>
  <country name="Singapore">
    <continent>Asia</continent>
    <holidays>      
    </holidays>
    <rank updated="yes">5</rank>
    <year>2011</year>
    <gdppc>59900</gdppc>
    <neighbor name="Malaysia" direction="N"/>
  </country>
</data>
import xml.etree.ElementTree as ET

xml_file = "my_tree.xml"

tree = ET.parse(xml_file)
root = tree.getroot()


newNode = ET.Element('christmas')
newNode.text = 'Yes'


root.insert(0, newNode)

上面,它直接插入到root. 如果我想将它插入一个名为的节点下方<holidays>(不知道它在真实数据中的深度级别),我如何指向root这个级别?谢谢。

标签: pythonxmlelementtree

解决方案


您快到了; 只需将您的最后一行替换为

target = root.find('.//holidays')    
target.insert(0, newNode)

看看它是否有效。


推荐阅读