Max Heiber
Max Heiber

Reputation: 15542

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

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.

Upvotes: 3

Views: 874

Answers (1)

alecxe
alecxe

Reputation: 474061

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>

Upvotes: 4

Related Questions