xml.etree.ElementTree parse - AttributeError: 'list' object has no attribute 'get'

xml.etree.ElementTree parse - AttributeError: 'list' object has no attribute 'get'

帮忙解析。我有一个文件,我想获得一个 ID。 当我尝试在 xml.etree.ElementTree 解析上使用 get('') 时,出现错误:

AttributeError: 'list' object has no attribute 'get'

我的代码是:

import xml.etree.ElementTree as ET

tree = ET.parse('sample.xml')   
root = tree.getroot()

for elem in root:

    print(elem.findall('alarmTime').get('id'))

我的 XML 文件是:

<?xml version="1.0" ?>
<zAppointments reminder="15">
    <appointment>
        <begin>1181251680</begin>
        <uid>040000008200E000</uid>
            <alarmTime id ='MAIN'>MONDAY</alarmTime>
                <STOP id='091'> OK </STOP>
                <DEF> NO </DEF>      
        <state></state>
        <location></location>
        <duration>1800</duration>
        <subject>Bring pizza home</subject>
    </appointment>
    <appointment>
        <begin>1234360800</begin>
        <duration>1800</duration>
            <subject>Check MS Office website for updates</subject>
            <location></location>
        <uid>604f4792-eb89-478b-a14f-dd34d3cc6c21-1234360800</uid>
        <state>dismissed</state>
    </appointment>
    <appointment>
        <begin>1181251680</begin>
        <uid>040000008200E000</uid>
            <alarmTime id ='SECOND'>SUNDAY</alarmTime>
                <STOP id='092'> OK-1 </STOP>
                <DEF> NO-1 </DEF>      
        <state></state>
        <location></location>
        <duration>1800</duration>
        <subject>Bring pizza home</subject>
    </appointment>
</zAppointments>

findall returns 一个列表,因此您不能在其上使用 get 方法。如果你确定 alarmTime 存在于 xml 的每个节点中,那么使用下面的代码

import xml.etree.ElementTree as ET

tree = ET.parse('sample.xml')   
root = tree.getroot()

for elem in root:

    print(elem.findall('alarmTime')[0].get('id'))

另一种可能的解决方案是使用 find 函数,但如果在元素节点

中找不到 alarmTime 则会抛出错误
import xml.etree.ElementTree as ET

tree = ET.parse('sample.xml')   
root = tree.getroot()

for elem in root:

    print(elem.find('alarmTime').get('id'))