Python parses XML file instance sharing

  • 2020-04-02 13:18:54
  • OfStack




def get_area_list(self):
        """ Gets a dictionary of regional province and city names """
        page = urllib2.urlopen(self.xml_url).read()
        area_list = {}
        root = ElementTree.fromstring(page)
        # read xml Format text 
        for onep in root:
            province =  onep.get('name')
            # In the parent tag name Data ( province C) 
            city_list = []
            for onec in onep:
                # In the subtag name Data ( city C) 
                city = onec.get('name')
                city_list.append(city)
            area_list[province] = city_list
            # Returns a dictionary of the relationship between a province and a city, i.e. : { Name of province: [ The city name 1 , city name 2, ・ ・ ・ ]}
        return area_list


Related articles: