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 .
Set the method
argument of tostring
to html
. As in:
etree.tostring(root, method="html")
Reference: Close a tag with no text in lxml
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With