简体   繁体   中英

Combine text and xml tag using python's ElementTree

I am trying to achieve something as below:

<root>
    <parent>Make from <child>12345678</child> this part</parent>
</root>

Leading text (ie "Make from") followed by a child tag followed by rest of the text (ie "this part") all within a parent tag in the exact sequence

An xml tag of the form: <parent-tag><leading-text> <child-tag> <trailing-text><parent-tag>

I am doing something as below, but the leading text gets overwritten

import xml.etree.ElementTree as ET

    root = ET.Element("root")

    b1 = ET.SubElement(root, "parent")
    b1.text = "Make from "
    b2 = ET.SubElement(b1, "child")
    b2.text = "12345678"

    b1.text = " this part"

    tree = ET.ElementTree(root)

and I get something as below

<root>
   <parent> this part <child>12345678</child> </parent>
</root>

Cannot find anything to append the trailing text to the existing leading text with the child tag in between.

Any pointers will help

Instead of:

b1.text = " this part"

try:

b2.tail = " this part"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM