Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

xml

lxml

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 .

like image 683
jhon.smith Avatar asked Oct 23 '13 13:10

jhon.smith


2 Answers

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

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

Reference: Close a tag with no text in lxml

like image 77
A. K. Tolentino Avatar answered Sep 22 '22 12:09

A. K. Tolentino


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>
like image 27
mzjn Avatar answered Sep 23 '22 12:09

mzjn