Note that dump
should only be used for debugging. Also, you should try to avoid mixing the lxml
and xml
libraries, even if they are quite similar. To answer your question, a tag with no content is generally written like this:
<COMPUTERLISTING />
This is the equivalent of <COMPUTERLISTING></COMPUTERLISTING>
.
You are getting None
because ElementTree.dump
writes to sys.stdout
instead of to a file. When you print the output of sys.stdout
, you are also printing the return value of sys.stdout
(which is None
):
>>> from lxml import etree
>>> listing = etree.Element("COMPUTERLISTING")
>>> etree.dump(listing) # returns normal sys.stdout output when you do not print
<COMPUTERLISTING>test</COMPUTERLISTING>
>>> print etree.dump(listing) # now also prints the None returned by sys.stdout
<COMPUTERLISTING>test</COMPUTERLISTING>
None
For a cleaner approach, you can do this instead:
>>> print etree.tostring(listing)
<COMPUTERLISTING/>
Or to use something similar to the string you were printing earlier (only with text):
>>> listing.text = 'test'
>>> print "STARTING_WITH:", etree.tostring(listing), "ENDS_WITH." # now with text
STARTING_WITH: <COMPUTERLISTING>test</COMPUTERLISTING> ENDS_WITH.