Home  >  Article  >  Backend Development  >  python解析xml文件实例分享

python解析xml文件实例分享

WBOY
WBOYOriginal
2016-06-06 11:28:08945browse

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn