如何使用ElementTree在父元素中的文本之间插入XML元素 [英] How can I insert an XML element between text in the parent element using ElementTree
本文介绍了如何使用ElementTree在父元素中的文本之间插入XML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想这样生成XML:
<Element>some text <Child>middle text</Child> some more text</Element>.
如何使用ElementTree?
How can I do this using ElementTree?
我在文档中找不到它。我认为 element#insert
是可以的,但这是为了在相对于其他孩子的特定位置插入孩子。
I couldn't find it in the docs. I thought element#insert
would work, but that's for inserting a child in a specific position relative to other children.
推荐答案
您需要定义子元素并将其设置为 .tail
,然后追加到父对象:
You need to define the child element and set it's .tail
, then append it to the parent:
import xml.etree.ElementTree as ET
parent = ET.Element("Element")
parent.text = "some text "
child = ET.Element("Child")
child.text = "middle text"
child.tail = " some more text"
parent.append(child)
print(ET.tostring(parent))
打印:
<Element>some text <Child>middle text</Child> some more text</Element>
这篇关于如何使用ElementTree在父元素中的文本之间插入XML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文