按名称将节点插入特定级别的 ElementTree 树

Insert node to ElementTree tree at specific level by name

如果我有一个深度未知的 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 指向该级别?谢谢。

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

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

看看它是否有效。

见下文

import xml.etree.ElementTree as ET

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>'''

root = ET.fromstring(xml)
holidays = root.find('.//holidays')
newNode = ET.Element('christmas')
newNode.text = 'Yes'
holidays.append(newNode)
ET.dump(root)