我有这个xml文件布局,我想提取所有子级名称(Amy、Max和Derek):
<data>
<dataentry>
<Name>John</Name>
<Birthday>3/3/93</BirthDay>
<Children>
<Child> Amy </Child>
<Child> Max </Child>
<Child> Derek </Child>
</Children>
</dataentry>
<dataentry>
....
</dataentry>
</data>
Python代码:
root = tree.getroot()
for dataentry in root.findall('dataentry'):
for children in dataentry.findall('Children'):
for child in children.findall('Child'):
print child.text
我有这个嵌套for循环,但是有没有更快更优雅的方法呢?你知道吗
您可以在单个循环中使用
xpath()
:考虑到
data
是你的根。你知道吗您可以使用SAX解析器来实现这一点。其思想是解析器将在遍历时执行操作,而不是将所有内容读入树中,然后再搜索子对象。这样既节省了内存又节省了时间。但是,这将打印所有
child
节点,而不考虑路径,因此它可能是您想要的,也可能不是您想要的。你知道吗相关问题 更多 >
编程相关推荐