覆盖 lxml 行为来为 Null 标记编写关闭和打开元素

jho*_*ith 5 python xml lxml

root = etree.Element('document')
rootTree = etree.ElementTree(root)
firstChild = etree.SubElement(root, 'test')
Run Code Online (Sandbox Code Playgroud)

输出是:

<document>
<test/>
</document
Run Code Online (Sandbox Code Playgroud)

我希望输出是:

<document>
<test>
</test>
</document>
Run Code Online (Sandbox Code Playgroud)

我知道两者是等效的,但是有没有办法获得我想要的输出。

Ghe*_*Ace 5

method将的参数设置tostringhtml。如:

etree.tostring(root, method="html")
Run Code Online (Sandbox Code Playgroud)

参考: 关闭lxml中没有文本的标签