gpt4 book ai didi

python - 在 ElementTree 中检查 XML 元素是否有子元素

转载 作者:太空狗 更新时间:2023-10-29 18:00:13 25 4
gpt4 key购买 nike

我以这种方式检索 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

我修改了你的示例,因为 item 根上的 findall 函数调用不起作用(因为 findall 将搜索直接后代,并且不是当前元素)。如果你想在你的工作程序之后访问子 child 的文本,你可以这样做:

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

不过这很适合递归。

关于python - 在 ElementTree 中检查 XML 元素是否有子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25950635/

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