我以这种方式检索XML文档:
import xml.etree.ElementTree as ET
root = ET.parse(urllib2.urlopen(url))
for child in root.findall("item"):
a1 = child[0].text # ok
a2 = child[1].text # ok
a3 = child[2].text # ok
a4 = child[3].text # BOOM
# ...
XML如下所示:
<item>
<a1>value1</a1>
<a2>value2</a2>
<a3>value3</a3>
<a4>
<a11>value222</a11>
<a22>value22</a22>
</a4>
</item>
如何检查a4
(在这种情况下,但可能是其他任何因素)是否有孩子?
您可以list
在元素上尝试该功能:
>>> xml = """<item>
<a1>value1</a1>
<a2>value2</a2>
<a3>value3</a3>
<a4>
<a11>value222</a11>
<a22>value22</a22>
</a4>
</item>"""
>>> root = ET.fromstring(xml)
>>> list(root[0])
[]
>>> list(root[3])
[<Element 'a11' at 0x2321e10>, <Element 'a22' at 0x2321e48>]
>>> len(list(root[3]))
2
>>> print "has children" if len(list(root[3])) else "no child"
has children
>>> print "has children" if len(list(root[2])) else "no child"
no child
>>> # Or simpler, without a call to list within len, it also works:
>>> print "has children" if len(root[3]) else "no child"
has children
我修改了您的示例,因为在根目录findall
上的函数调用item
不起作用(findall
将搜索直接后代,而不是当前元素)。如果以后要在工作程序中访问子孩子的文本,则可以执行以下操作:
for child in root.findall("item"):
# if there are children, get their text content as well.
if len(child):
for subchild in child:
subchild.text
# else just get the current child text.
else:
child.text
不过,这将非常适合递归。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句