Home > Mobile >  reading a .osm file in pandas, python using xml.etree.ElementTree
reading a .osm file in pandas, python using xml.etree.ElementTree

Time:02-15

Hi I am trying to read a .osm file in pandas using xml.etree.ElementTree. How to fetch the id inside node and the values of tag k = "" v = ""

Input:

<osm version="0.6" generator="CGImap 0.8.6 (895960 spike-06.openstreetmap.org)" copyright="OpenStreetMap and contributors" attribution="http://www.openstreetmap.org/copyright" license="http://opendatacommons.org/licenses/odbl/1-0/">
 <bounds minlat="12.5770000" minlon="-2.9532000" maxlat="12.6328000" maxlon="-2.8514000"/>
 <node id="902955577" visible="true" version="6" changeset="90170478" timestamp="2020-08-31T06:29:59Z" user="pizzaiolo" uid="1772368" lat="12.6049118" lon="-2.9023135">
  <tag k="admin_level" v="8"/>
  <tag k="capital" v="8"/>
  <tag k="description" v="Commune rurale"/>
  <tag k="is_in" v="Toma;Nayala;Boucle du Mouhoun;Burkina Faso;Africa"/>
  <tag k="is_in:continent" v="Africa"/>
  <tag k="is_in:country" v="Burkina Faso"/>
  <tag k="is_in:country_code" v="BF"/>
  <tag k="is_in:department" v="Toma"/>
  <tag k="is_in:province" v="Nayala"/>
  <tag k="is_in:province_code" v="40"/>
  <tag k="is_in:region" v="Boucle du Mouhoun"/>
  <tag k="is_in:region_code" v="02"/>
  <tag k="name" v="Goa"/>
  <tag k="name:fr" v="Goa"/>
  <tag k="note" v="Inserted by script"/>
  <tag k="place" v="village"/>
  <tag k="population" v="651"/>
  <tag k="source" v="NGA GEOnet Names Server (GNS)"/>
  <tag k="source:population" v="INSD.BF"/>
  <tag k="wikidata" v="Q13414957"/>
 </node>

Code:

from xml.etree.ElementTree import parse
import pandas as pd

mydata = parse('map.osm')
print(mydata,'\n')

my_id=[]

for item in mydata.iterfind('node'):
    my_id.append(item.findtext('id'))
    
print(my_id)

Output: <xml.etree.ElementTree.ElementTree object at 0x0000018504B10160>

[None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None]

CodePudding user response:

findtext looks for an element, but id is not an element; it's an attribute. You want item.attrib['id'], or perhaps item.get('id').

  • Related