Python ElementTree无法访问所有子级

2024-04-26 04:41:14 发布

您现在位置:Python中文网/ 问答频道 /正文


我正在编写一个小python程序,用ElementTree从xml文件创建一个文件夹结构。但是如果我试图调用根元素上的findAll(<tagname>),我总是会得到错误:“'element'对象没有属性'findAll'”。但是如果我深入到树中并调用“season”标记上的findAll()方法,它就可以正常工作。是什么导致了这个问题?你知道吗

下面是加载xml的方法:

import xml.etree.ElementTree as ET

videodata = ET.parse(<xml-file>).getroot()
for show in videodata.findAll('show'): #throws the above exception
    #do stuff
for season in videodata.find('show').findAll('season'): #throws the above exception
    #do stuff
for episode in videodata.find('show').find('season').findAll('episode'): #works
    #do stuff

这是我的xml文件:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<tvshows>
    <show name="" cover="">
        <season number="1"></season>
        <season number="2"></season>
        <season number="3"></season>
        <season number="4"></season>
        <season number="5"></season>
        <season number="6">
            <episode number="1"/>
            <episode number="2"/>
            <episode number="3"/>
            <episode number="4"/>
        </season>
        <season number="7"></season>
    </show>
    <show name="" cover="">
        <season number="1"></season>
        <season number="2"></season>
        <season number="3"></season>
        <season number="4"></season>
        <season number="5"></season>
    </show>
</tvshows>

Tags: 方法innumberforshowxmlfinddo

热门问题