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

输出是:

<document>
<test/>
</document

我希望输出为:

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

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

4

2 回答 2

4

Set the method argument of tostring to html. As in:

etree.tostring(root, method="html")

Reference: Close a tag with no text in lxml

于 2015-12-10T02:27:53.717 回答
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>
于 2013-10-23T17:25:02.797 回答