Home > Article > Backend Development > python解析xml文件实例分享
代码如下:
def get_area_list(self):
"""获取地域省份和城市名称字典"""
page = urllib2.urlopen(self.xml_url).read()
area_list = {}
root = ElementTree.fromstring(page)
#读取xml格式文本
for onep in root:
province = onep.get('name')
#父标签中的name数据(province中)
city_list = []
for onec in onep:
#子标签中的name数据(city中)
city = onec.get('name')
city_list.append(city)
area_list[province] = city_list
#返回一个省份与城市关系的字典,即:{省份名称:[城市名称1,城市名称2,···]}
return area_list