Paranth
Paranth

Reputation: 59

How can i read the text between xml tags using xml.etree.Elementree ?If the xml is complex

<GeocodeResponse>
<status>OK</status>
<result>
<type>locality</type>
<type>political</type>
<formatted_address>Chengam, Tamil Nadu 606701, India</formatted_address>
<address_component>
<long_name>Chengam</long_name>
<short_name>Chengam</short_name>
<type>locality</type>
<type>political</type>
</address_component>
<address_component>
<long_name>Tiruvannamalai</long_name>
<short_name>Tiruvannamalai</short_name>
<type>administrative_area_level_2</type>
<type>political</type>
</address_component>
<address_component>
<long_name>Tamil Nadu</long_name>
<short_name>TN</short_name>
<type>administrative_area_level_1</type>
<type>political</type>
</address_component>
<address_component>
<long_name>India</long_name>
<short_name>IN</short_name>
<type>country</type>
<type>political</type>
</address_component>
<address_component>
<long_name>606701</long_name>
<short_name>606701</short_name>
<type>postal_code</type>
</address_component>
<geometry>
<location>
<lat>12.3067864</lat>
<lng>78.7957856</lng>
</location>
<location_type>APPROXIMATE</location_type>
<viewport>
<southwest>
<lat>12.2982423</lat>
<lng>78.7832165</lng>
</southwest>
<northeast>
<lat>12.3213030</lat>
<lng>78.8035583</lng>
</northeast>
</viewport>
<bounds>
<southwest>
<lat>12.2982423</lat>
<lng>78.7832165</lng>
</southwest>
<northeast>
<lat>12.3213030</lat>
<lng>78.8035583</lng>
</northeast>
</bounds>
</geometry>
<place_id>ChIJu8JCb3jxrDsRAOfhACQczWo</place_id>
</result>
</GeocodeResponse>

I am new to xml thing and i don't know how to handle it with python xml.etree ? Basic stuffs i read from https://docs.python.org/2/library/xml.etree.elementtree.html#parsing-xml is useful,but still struggling to printout the latitude and longitude values under geometry-->location.i have tried something like this

        with open('data.xml', 'w') as f:
            f.write(xmlURL.text)
        tree = ET.parse('data.xml')
        root = tree.getroot()
        lat = root.find(".//geometry/location")
        print(lat.text)

Upvotes: 0

Views: 48

Answers (1)

DeepSpace
DeepSpace

Reputation: 81614

You almost got it. Change root.find(".//geometry/location") to root.find(".//geometry/location/lat"):

lat = root.find(".//geometry/location/lat")
print(lat.text)
>> 12.3067864

Same goes for lng of course:

lng = root.find(".//geometry/location/lng")
print(lng.text)
>> 78.7957856

Upvotes: 1

Related Questions