[英]Python xml ElementTree findall returns empty result
I would like to parse following XML file using the Python xml ElementTree API.我想使用 Python xml ElementTree API 解析以下 XML 文件。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<foos>
<foo_table>
<!-- bar -->
<fooelem>
<fname>BBBB</fname>
<group>SOMEGROUP</group>
<module>some module</module>
</fooelem>
<fooelem>
<fname>AAAA</fname>
<group>other group</group>
<module>other module</module>
</fooelem>
<!-- bar -->
</foo_table>
</foos>
In this example code I try to find all the elements under /foos/foo_table/fooelem/fname
but obviously findall
doesn't find anything when running this code.在此示例代码中,我尝试查找
/foos/foo_table/fooelem/fname
下的所有元素,但显然findall
在运行此代码时找不到任何内容。
import xml.etree.cElementTree as ET
tree = ET.ElementTree(file="min.xml")
for i in tree.findall("./foos/foo_table/fooelem/fname"):
print i
root = tree.getroot()
for i in root.findall("./foos/foo_table/fooelem/fname"):
print i
I am not experienced with the ElementTree API, but I've used the example under https://docs.python.org/2/library/xml.etree.elementtree.html#example .我对 ElementTree API 没有经验,但我使用了https://docs.python.org/2/library/xml.etree.elementtree.html#example下的示例。 Why is it not working in my case?
为什么它在我的情况下不起作用?
foos
is your root
, you would need to start findall
below, eg foos
是你的root
,你需要在下面开始findall
,例如
root = tree.getroot()
for i in root.findall("foo_table/fooelem/fname"):
print i.text
Output:输出:
BBBB
AAAA
This is because the path you are using begins BEFORE the root element ( foos
).这是因为您使用的路径在根元素 (
foos
) 之前开始。
Use this instead: foo_table/fooelem/fname
改用这个:
foo_table/fooelem/fname
findall
doesn't work, but this does: findall
不起作用,但这样做:
e = xml.etree.ElementTree.parse(myfile3).getroot()
mylist=list(e.iter('checksum'))
print (len(mylist))
mylist will have the proper length. mylist 将具有适当的长度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.