2014-10-10 87 views
0

这里是我的示例代码:找不到标签

import xml.etree.cElementTree as ET 

g = ET.Element('stuff') 
g.set('foo','bar') 
h = ET.ElementTree(g) 

使用这个配置,这里发生了什么:

>>> g.iterfind('stuff') 
<generator object select at 0x10d38fa00> 
>>> _.next() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
StopIteration 

>>> h.iterfind('stuff') 
<generator object select at 0x10d38fa00> 
>>> _.next() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
StopIteration 

我真的宁愿不要使用getiterator()并且每次迭代整个树(尽管我猜iterfind可能会在后台做这件事)。为什么它找不到这个东西?它在我做set之前工作,但不是之后。

+0

确定它在你执行'set'之前是否有效?它不适合我,也不适合。你的'stuff'节点没有任何名为'stuff'的后代,所以'iterfind'(或'find',这对于交互式调试来说更容易一点)不会返回任何内容。 – abarnert 2014-10-10 22:03:38

回答

0

在这里找不到任何东西。您创建了一个没有子节点的stuff节点,然后向其请求所有节点stuff,其中没有节点。

它不会在set前工作比后更多:

>>> import xml.etree.cElementTree as ET 
>>> g = ET.Element('stuff') 
>>> print g.find('stuff') 
None 
>>> next(g.iterfind('stuff')) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
StopIteration 

如果你把那下另一个节点,它的作品有或没有set上任何一个:

>>> f = ET.Element('parent') 
>>> f.append(g) 
>>> print f.find('stuff') 
<Element 'stuff' at 0x10edc5b10> 
>>> f.set('foo', 'bar') 
>>> g.set('foo', 'bar') 
>>> print f.find('stuff') 
<Element 'stuff' at 0x10edc5b10>