root = etree.Element('document')
rootTree = etree.ElementTree(root)
firstChild = etree.SubElement(root, 'test')
输出结果为:
<document>
<test/>
</document
我希望输出为:
<document>
<test>
</test>
</document>
我知道两者都是等价的,但是有办法获得我想要的输出。
答案 0 :(得分:4)
答案 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>