root = etree.Element('document')
rootTree = etree.ElementTree(root)
firstChild = etree.SubElement(root, 'test')
输出是:
<document>
<test/>
</document
我希望输出为:
<document>
<test>
</test>
</document>
我知道两者是等价的,但有没有办法获得我想要的输出。
Set the method
argument of tostring
to html
. As in:
etree.tostring(root, method="html")
Reference: Close a tag with no text in lxml
您可以这样做:
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>