Skip to content Skip to sidebar Skip to footer

Override Lxml Behavior To Write A Closing And Opening Element For Null Tags

root = etree.Element('document') rootTree = etree.ElementTree(root) firstChild = etree.SubElement(root, 'test') The output is:

Solution 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

Solution 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>

Post a Comment for "Override Lxml Behavior To Write A Closing And Opening Element For Null Tags"