覆盖lxml行为以写入Null标记的结束和打开元素

时间:2013-10-23 13:43:42

标签: python xml lxml

root = etree.Element('document')
rootTree = etree.ElementTree(root)
firstChild = etree.SubElement(root, 'test')

输出结果为:

<document>
<test/>
</document

我希望输出为:

<document>
<test>
</test>
</document>

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

2 个答案:

答案 0 :(得分:4)

method的{​​{1}}参数设置为tostring。如:

html

参考:Close a tag with no text in lxml

答案 1 :(得分:3)

以下是如何做到这一点:

from lxml import etree

root = etree.Element('document')
rootTree = etree.ElementTree(root)
firstChild = etree.SubElement(root, 'test')

print etree.tostring(root, pretty_print=True)

# Set empty string as element content to force open and close tags
firstChild.text = ''

print etree.tostring(root, pretty_print=True)

输出:

<document>
  <test/>
</document>

<document>
  <test></test>
</document>