Close A Tag With No Text In Lxml
I am trying to output a XML file using Python and lxml However, I notice one thing that if a tag has no text, it does not close itself. An example of this would be: root = etree.El
Solution 1:
Note that <test></test>
and <test/>
mean exactly the same thing. What you want is for the test-tag to actually do have a text that consists in a single linebreak. However, an empty tag with no text is usually written as <test/>
and it makes very little sense to insist on it to appear as <test></test>
.
Solution 2:
To clarify @ymv answer in case it might be of help to others:
from lxml import etree
root = etree.Element('document')
rootTree = etree.ElementTree(root)
firstChild = etree.SubElement(root, 'test')
print(etree.tostring(root, method='html'))
### b'<document><test></test></document>'
Solution 3:
Use lxml.html.tostring to serialize to HTML
import lxml.html
root = lxml.html.fromstring(mydocument)
print(lxml.html.tostring(root))
Solution 4:
Use empty string '' like this:
root = etree.Element('document')
etree.SubElement(root, 'test').text =''
Post a Comment for "Close A Tag With No Text In Lxml"