gpt4 book ai didi

python - Elementtree 转储给出错误答案

转载 作者:行者123 更新时间:2023-11-28 22:49:58 25 4
gpt4 key购买 nike

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.

虽然我今天又病又累,但我不明白。一旦我开始添加元素,不匹配的标签就会得到纠正,因此它本身不是一个障碍,但幻影 None 仍然是我所做的一切。是什么赋予了?我已经留下了进口产品,以防它们出现问题。

最佳答案

请注意 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.

关于python - Elementtree 转储给出错误答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23173231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com