Send xml file using python

Reading the data from overpass-API, I have no problem getting the basic fields. From the below example, the lat and lon are easily read. What I cannot manage is the read the various tags with K=xxxx, v=yyyyy ; I need to read the one with k="name" so as to build a list of city name, lat, lon.

The data included in this document is from The data is made available under ODbL.

<node id="31024030" lat="51.0763933" lon="4.7224848">
  <tag k="is_in" v="Antwerpen, Belgium, Europe"/>
  <tag k="is_in:continent" v="Europe"/>
  <tag k="is_in:country" v="Belgium"/>
  <tag k="is_in:province" v="Antwerp"/>
  <tag k="name" v="Heist-op-den-Berg"/>
  <tag k="openGeoDB:auto_update" v="population"/>
  <tag k="openGeoDB:is_in" v="Heist-op-den-Berg,Heist-op-den-Berg,Mechelen,Mechelen,Antwerpen,Antwerpen,Vlaanderen,Vlaanderen,Belgique,Belgique,Europe"/>

Code that I have as yet:
import xml.etree.cElementTree as ET
tree = ET.parse('target.osm')
root = tree.getroot()
for node in allnodes:
 cityname='' # set default in case proper tag not found
 for tag in node.getiterator():
     print tag.attrib
     # add code here to get the cityname
  print lat,lon,cityname

Last updated:11/6/2014 12:46:30 AM

1 Answers

Pravesh Singh
Pravesh Singh

You need to iterate over all children of each node and search for an element with a k="name" attribute:

for tag in node.findall('tag'):
    if tag.attrib['k'] == 'name':
        cityname = tag.attrib['v']

Or by using your get() approach:

for tag in node.findall('tag'):
    if tag.get('k') == 'name':
        cityname = tag.get('v')