from lxml import etree
from xml.etree.ElementTree import Element, SubElement, dump

listing = Element("COMPUTERLISTING")
print "STARTING_WITH:", dump(listing),"ENDS_WITH."

This outputs...
STARTING_WITH:<COMPUTERLISTING />
None ENDS_WITH.

I thought it should be...
STARTING_WITH:<COMPUTERLISTING></COMPUTERLISTING> 
ENDS_WITH.

I don't get it though I am both ill and tired today. The unmatched tags are corrected once I start adding elements so it's not a showstopper as such but the phantom None remains whatever I do. What gives? I've left the imports in just in case there's something wrong with them.

有帮助吗?

解决方案

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.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top