作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我想在一个 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/
我是一名优秀的程序员,十分优秀!