SEND XML FILE USING PYTHON

Chintoo Semi

Total Post:135

Points:947
Posted by  Chintoo Semi
XML
 1101  View(s)
Ratings:
Rate this:

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 www.openstreetmap.org. 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()

allnodes=root.findall('node')

for node in allnodes:

   lat=node.get('lat')

   lon=node.get('lon')

 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

  1. Pravesh Singh

    Post:412

    Points:2888
    Re: Send xml file using python

    You need to iterate over all children of each node and search for a 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')

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!