【问题标题】:Access element and tag in xml file using ElementTree使用 ElementTree 访问 xml 文件中的元素和标签
【发布时间】:2017-09-18 12:20:06
【问题描述】:

非常感谢您的阅读。对于这样一个初学者的问题,我深表歉意,因为我确信这是一个简单的答案。非常感谢任何指导。

我有一个 xml 文件,我正在用 ElementTree 解析它,其中的元素如下所示:

data.xml:
<?xml version="1.0" encoding="utf-8"?><listings><listing id="26496000" dateFirstListed="2012-10-13" dateLastListed="2013-10-06" market="SALE" propertyType="DETACHED" bedrooms="4" latestAskingPrice="314950"><address key="u935d·0" udprn="50812465" line1="12 Millcroft" line2="Millhouse Green" town="SHEFFIELD" postcode="S36 9AR" /><description>  SOME TEXT HERE </description></listing>

我想访问&lt;description&gt;标签和&lt;address key&gt;

使用https://docs.python.org/2/library/xml.etree.elementtree.html 中列出的指南我写道:

import xml.etree.ElementTree
data = xml.etree.ElementTree.parse('data.xml')
root = data.getroot()

并遍历子元素:

for child in root:
    print child.tag, child.attrib
>
listing {'dateLastListed': '2013-10-06', 'dateFirstListed': '2012-10-13', 'propertyType': 'DETACHED', 'latestAskingPrice': '314950', 'bedrooms': '4', 'id': '26496000', 'market': 'SALE'}

这只会给我&lt;listing&gt; 标签的子元素。如何更改上述表达式以访问&lt;address key&gt;&lt;description&gt;

编辑:遵循这个问题Parsing XML with Python - accessing elements的指导

我试着写了:

for i in root.findall("listing"):
    description = i.find('description')
    print description.text

    >
    AttributeError: 'NoneType' object has no attribute 'text'

【问题讨论】:

    标签: python html xml parsing elementtree


    【解决方案1】:

    您可以逐个遍历列表,然后获取内部 descriptionaddress 子元素。要访问属性,请使用.attrib attribute

    import xml.etree.ElementTree as ET
    
    
    data = ET.parse('data.xml')
    root = data.getroot()
    for listing in root.findall("listing"):
        address = listing.find('address')
        description = listing.findtext('description')
    
        print(description, address.attrib.get("key"))
    

    【讨论】:

    • 嗨@alecxe 感谢您的意见。我之前实际上尝试过这个(我刚刚用这个更新了我的答案),并得到了错误AttributeError: 'NoneType' object has no attribute 'text' 当我删除描述行并打印部分时,我确实得到了地址列表ids,但描述总是返回为nonetype 即为空。
    • @ChuckM 好吧,可能不是每个列表都有描述。更新了答案,看看吧。
    • 哎呀,我应该说,是的,就是这样。谢谢。这工作得很好:)
    猜你喜欢
    • 1970-01-01
    • 2016-09-17
    • 2019-06-17
    • 2017-05-24
    • 2014-07-04
    • 2018-08-27
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    相关资源
    最近更新 更多