【问题标题】:xml.etree.ElementTree parse - AttributeError: 'list' object has no attribute 'get'xml.etree.ElementTree 解析 - AttributeError:“列表”对象没有属性“获取”
【发布时间】:2018-02-15 08:16:24
【问题描述】:

帮助解析。我有一个文件,我想获得一个 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>

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-15
      • 2021-07-05
      • 2018-03-14
      • 1970-01-01
      • 1970-01-01
      • 2018-01-16
      • 2016-05-14
      • 2016-12-21
      相关资源
      最近更新 更多