xml.etree.ElementTree parse - AttributeError:'list'对象没有属性'get'

时间:2018-02-15 08:16:25

标签: xml python-3.x xml.etree

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

  

AttributeError:'list'对象没有属性'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>

1 个答案:

答案 0 :(得分:0)

findall会返回一个列表,因此您无法使用get方法。如果您确定在xml的每个节点中都存在alarmTime,那么请使用下面的代码

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'))