简体   繁体   English

使用 python 的 ElementTree 组合文本和 xml 标签

[英]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前导文本(即“Make from”)后跟一个子标签,后跟文本的 rest(即“这部分”),所有这些都在父标签中按确切顺序

An xml tag of the form: <parent-tag><leading-text> <child-tag> <trailing-text><parent-tag>一个 xml 标签的形式: <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.找不到 append 的任何内容,现有前导文本的尾随文本与子标签之间。

Any pointers will help任何指针都会有所帮助

Instead of:代替:

b1.text = " this part"

try:尝试:

b2.tail = " this part"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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