问题
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