#!/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>