【问题标题】:Multiple text nodes in Python's ElementTree? HTML generationPython的ElementTree中有多个文本节点? HTML 生成
【发布时间】:2010-06-29 21:47:39
【问题描述】:

我正在使用 ElementTree 生成一些 HTML,但我遇到了 ElementTree 不将文本存储为节点的问题,而是将文本存储为 texttexttail 属性。如果我想生成需要多个文本节点的东西,这是一个问题,例如:

<a>text1 <b>text2</b> text3 <b>text4</b> text5</a>

据我所知,没有办法生成这个——我错过了什么吗?或者,是否有更好的解决方案可以在 Python 中快速简单地生成 HTML?

【问题讨论】:

    标签: python elementtree html-generation


    【解决方案1】:

    要使用ElementTree 生成上述字符串,您可以使用以下代码。诀窍在于,text 是下一个元素之前的第一批文本,tail 是该元素之后直到下一个元素的所有文本。

    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>
    

    【讨论】:

    • "tail 是元素之后直到下一个元素的所有文本。"啊,这是我没有意识到的。谢谢!
    猜你喜欢
    • 2015-05-11
    • 1970-01-01
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    • 2019-07-14
    • 1970-01-01
    • 2015-05-28
    • 2011-01-11
    相关资源
    最近更新 更多