大家好!我正在尝试创建一个使用Google的Geocode API(XML)的应用程序。这是我正在使用的XML数据:
<GeocodeResponse>
<status>OK</status>
<result>
<type>establishment</type>
<type>point_of_interest</type>
<type>university</type>
<formatted_address>77 Massachusetts Ave, Cambridge, MA 02139, USA</formatted_address>
<address_component>
<long_name>77</long_name>
<short_name>77</short_name>
<type>street_number</type>
</address_component>
<address_component>
<long_name>Massachusetts Avenue</long_name>
<short_name>Massachusetts Ave</short_name>
<type>route</type>
</address_component>
<address_component>
<long_name>Area 2/MIT</long_name>
<short_name>Area 2/MIT</short_name>
<type>neighborhood</type>
<type>political</type>
</address_component>
<address_component>
<long_name>Cambridge</long_name>
<short_name>Cambridge</short_name>
<type>locality</type>
<type>political</type>
</address_component>
<address_component>
<long_name>Middlesex County</long_name>
<short_name>Middlesex County</short_name>
<type>administrative_area_level_2</type>
<type>political</type>
</address_component>
<address_component>
<long_name>Massachusetts</long_name>
<short_name>MA</short_name>
<type>administrative_area_level_1</type>
<type>political</type>
</address_component>
<address_component>
<long_name>United States</long_name>
<short_name>US</short_name>
<type>country</type>
<type>political</type>
</address_component>
<address_component>
<long_name>02139</long_name>
<short_name>02139</short_name>
<type>postal_code</type>
</address_component>
<geometry>
<location>
<lat>42.3600910</lat>
<lng>-71.0941600</lng>
</location>
<location_type>ROOFTOP</location_type>
<viewport>
<southwest>
<lat>42.3587420</lat>
<lng>-71.0955090</lng>
</southwest>
<northeast>
<lat>42.3614400</lat>
<lng>-71.0928110</lng>
</northeast>
</viewport>
</geometry>
<place_id>ChIJh2oa9apw44kRPCAIs6WO4NA</place_id>
</result>
</GeocodeResponse>
我正在尝试通过XML数据来提取县:
<address_component>
<long_name>Middlesex County</long_name>
<short_name>Middlesex County</short_name>
<type>administrative_area_level_2</type>
<type>political</type>
</address_component>
但是,XML数据中的其他标记使用相同名称“address_component”和“long_name”。由于没有与这些标签相关的属性,我无法找到我想要的特定数据。谁能帮助我如何使用python浏览XML数据并找到我需要的确切数据,尽管这些标签具有相同的名称?
答案 0 :(得分:0)
如果您打算使用子元素address_component
获取type=administrative_area_level_2
,则可以迭代XML并选择所需的元素:
import xml.etree.ElementTree as ET
root = ET.fromstring("your xml string")
def find_by_tag(tag, add_type= "administrative_area_level_2"):
for address in root.iter("address_component"):
if address.find("type").text == add_type:
return address.find(tag).text
return None
您可以使用函数long_name
获取find_by_tag
:
find_by_tag("long_name")
## 'Middlesex County'
或其他标签,例如:
find_by_tag("short_name")
## 'Middlesex County'
find_by_tag("short_name", "postal_code")
## '02139'