Python的ElementTree中有多个文本节点? HTML生成 [英] Multiple text nodes in Python's ElementTree? HTML generation
问题描述
我正在使用ElementTree生成一些HTML,但是我遇到了一个问题,即ElementTree不将文本存储为Node,而是存储为Element
的text
和tail
属性.如果我要生成需要多个文本节点的内容,那么这将是一个问题,例如:
I'm using ElementTree to generate some HTML, but I've run into the problem that ElementTree doesn't store text as a Node, but as the text
and tail
properties of Element
. This is a problem if I want to generate something that would require multiple text nodes, for example:
<a>text1 <b>text2</b> text3 <b>text4</b> text5</a>
据我所知,没有办法产生这个-我错过了什么吗?还是有更好的解决方案,可以在Python中快速,简单地生成HTML?
As far as I can tell there is no way to generate this- am I missing something? Or, is there a better solution for quick and simple HTML generation in Python?
推荐答案
要使用ElementTree
生成上述字符串,可以使用以下代码.诀窍在于,text
是下一个元素之前的第一批文本,而tail
是该元素之后到下一个元素的所有文本.
To generate the above string with ElementTree
you can use the following code. The trick to this is that the text
is the very first lot of text before the next element and the tail
is all the text after the element up to the next element.
import xml.etree.ElementTree as ET
root = ET.Element("a")
root.text = 'text1 ' #First Text in the Element a
b = ET.SubElement(root, "b")
b.text = 'text2' #Text in the first b
b.tail = ' text3 ' #Text immediately after the first b but before the second
b = ET.SubElement(root, "b")
b.text = 'text4'
b.tail = ' text5'
print ET.tostring(root)
#This prints <a>text1 <b>text2</b> text3 <b>text4</b> text5</a>
这篇关于Python的ElementTree中有多个文本节点? HTML生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!