Elementtree转储给出了错误的答案

时间:2014-04-19 17:32:52

标签: python elementtree xml.etree

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.

虽然今天我既病又累,但我没有得到它。一旦我开始添加元素就会纠正不匹配的标签,因此它不是一个showstopper,但幻像None仍然是我做的。是什么赋予了?我已经离开了进口,以防它们出现问题。

1 个答案:

答案 0 :(得分:4)

请注意,dump仅应用于调试。此外,您应该尽量避免混合lxmlxml库,即使它们非常相似。要回答您的问题,没有内容的标记通常是这样写的:

<COMPUTERLISTING />

这相当于<COMPUTERLISTING></COMPUTERLISTING>

您收到None因为ElementTree.dump写入sys.stdout而不是文件。当您打印sys.stdout的输出时,您还打印了sys.stdout的返回值(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

为了更清洁的方法,您可以改为:

>>> print etree.tostring(listing)
<COMPUTERLISTING/>

或者使用与之前打印的字符串类似的东西(仅限文字):

>>> listing.text = 'test'
>>> print "STARTING_WITH:", etree.tostring(listing), "ENDS_WITH."  # now with text
STARTING_WITH: <COMPUTERLISTING>test</COMPUTERLISTING> ENDS_WITH.