Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用';后找不到标记;设置';使用cElementTree库创建元素的方法_Python_Xml_Elementtree - Fatal编程技术网

Python 使用';后找不到标记;设置';使用cElementTree库创建元素的方法

Python 使用';后找不到标记;设置';使用cElementTree库创建元素的方法,python,xml,elementtree,Python,Xml,Elementtree,以下是我的示例代码: 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 re

以下是我的示例代码:

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
>g.iterfind('stuff'))
>>>(下)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
停止迭代
>>>h.iterfind(“东西”)
>>>(下)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
停止迭代

我真的不希望每次都使用
getiterator()
并遍历整个树(尽管我猜iterfind可能是在幕后这样做的)。为什么它找不到东西?它在我设置
之前工作,但在设置之后不起作用。

在这里找不到任何东西。您已经创建了一个没有子节点的
stuff
节点,然后要求它提供其所有后代
stuff
节点,而这些节点都没有子节点

设置之前和设置之后都不起作用:

>>> 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

在执行
设置之前,您确定它可以工作吗?这不适合我,也不应该。您的
stuff
节点没有任何名为
stuff
的子体,因此
iterfind
(或者
find
,这对于交互式调试来说更容易使用)不返回任何内容。
>>> 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>