python - 按名称将节点插入到特定级别的 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
这个级别?谢谢。
解决方案
您快到了; 只需将您的最后一行替换为
target = root.find('.//holidays')
target.insert(0, newNode)
看看它是否有效。
推荐阅读
- kubernetes - Kubernetes 入口 - 访问 Web 服务容器子路径
- r - 条件数据帧切片
- c# - ef core 多 1 比 1 或零同级
- r - 从仅包含标题的 CSV 文件中设置列的数据类型
- python - 为什么 mysql.connector.connect 因内部错误而失败?
- rest - 为什么服务器响应状态为 400
- reactjs - 路由 - 重定向(Next JS)
- r - 将列表名称与函数输入匹配
- python - 需要通过 xpath 选择元素的动态 python selenium 方式
- python - python:如何创建以元组形式为来自 A 和 B 的整数生成所有可能组合的东西