How can I insert an XML element between text in the parent element using ElementTree

人走茶凉 提交于 2020-06-26 07:28:18

问题


I want to generate XML like this:

<Element>some text <Child>middle text</Child> some more text</Element>.

How can I do this using ElementTree?

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.


回答1:


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

Prints:

<Element>some text <Child>middle text</Child> some more text</Element>


来源:https://stackoverflow.com/questions/38579478/how-can-i-insert-an-xml-element-between-text-in-the-parent-element-using-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!