gpt4 book ai didi

Python 元素树 : How to add SubElement at VERY specific position?

转载 作者:数据小太阳 更新时间:2023-10-29 02:30:01 26 4
gpt4 key购买 nike

我想在一个 xml 文件中添加一个子元素,但在一个非常具体的位置,而不是附加到末尾。

标准方式是:

subi = ET.SubElement(root[0][0], 'subi')

这很好。

但是:假设 root[0][0] 已经有两个 child ,因此可以通过 root[0][0][0] 和 root[0][0][1] 访问。

而且我想让“subi”成为新的中间 child root[0][0][1],使原来的第二个 child 成为第三个 child root[0][0][2]。

有办法吗? (我对生活和自然的体验会说没有,但我对python寄予厚望=)

最佳答案

您可以使用 Element.insert方法。它允许您指定索引。

例如,在第 3 个(索引:2)元素之前插入:

>>> import xml.etree.ElementTree as ET
>>>
>>> root = ET.fromstring('''
... <root>
... <first></first>
... <second></second>
... <third></third>
... </root>
... ''')
>>>
>>> new = ET.Element('new')
>>> root.insert(2, new) # <-----------
>>> print(ET.tostring(root))
<root>
<first />
<second />
<new /><third />
</root>

关于Python 元素树 : How to add SubElement at VERY specific position?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25824920/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com