Python:xml.etree.ElementTree模块简单封装

#!/usr/bin/env python
# coding:UTF-8


"""
@version: python3.x
@author:曹新健
@contact: 617349013@qq.com
@software: PyCharm
@file: xml.etree.ElementTree模块简单封装.py
@time: 2018/11/14 16:19
"""


try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET




def get_element_children(element):
        return (child for child in element)

def get_element_children_dict(element):
    child_dict = {}
    for child in element:
        child_dict[child.tag] = child.text
    return child_dict

def get_element_attrib_dict(element):
    return element.attrib

if __name__ == '__main__':
    tree = ET.parse("country_data.xml")
    root = tree.getroot()
    for element in tree.findall("country"):
        print(get_element_children_dict(element))

    neighbor_element = tree.find("country/neighbor")
    print(get_element_attrib_dict(neighbor_element))

 

country_data.xml
<data>
    1111
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2018</year>
        <gdppc>141100</gdppc>
        <neighbor direction="E" name="Austria" />
        <neighbor direction="W" name="Switzerland" />
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2018</year>
        <gdppc>59900</gdppc>
        <neighbor direction="N" name="Malaysia" />
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2018</year>
        <gdppc>13600</gdppc>
        <neighbor direction="W" name="Costa Rica" />
        <neighbor direction="E" name="Colombia" />
    </country>
</data>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值