Override lxml behavior to write a closing and opening element for Null tags

本秂侑毒 提交于 2020-01-14 13:07:32

问题


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

The output is:

<document>
<test/>
</document

I want the output to be:

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

I know both are equivalent but is there a way to get the output that i want .


回答1:


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

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

Reference: Close a tag with no text in lxml




回答2:


Here is how you can do it:

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)

Output:

<document>
  <test/>
</document>

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


来源:https://stackoverflow.com/questions/19543399/override-lxml-behavior-to-write-a-closing-and-opening-element-for-null-tags

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!