Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close a tag with no text in lxml

Tags:

python

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.Element('document')
rootTree = etree.ElementTree(root)
firstChild = etree.SubElement(root, 'test')

The output of this is:

<document>
<test/>
</document

I want the output to be:

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

So basically I want to close a tag which has no text, but is used to the attribute value. How do I do that? And also, what is such a tag called? I would have Googled it, but I don't know how to search for it.

like image 516
user225312 Avatar asked May 05 '10 07:05

user225312


2 Answers

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

like image 76
Frank Avatar answered Sep 30 '22 08:09

Frank


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>'
like image 40
gongzhitaao Avatar answered Sep 30 '22 07:09

gongzhitaao