2014-09-29 43 views
1

從overpass-API讀取數據,我沒有問題獲取基本字段。從下面的例子中,lat和lon很容易讀取。我不能管理的是讀取K = xxxx,v = yyyyy;我需要閱讀k =「name」的那一個,以便建立一個城市名稱lat,lon的列表。python OSM xml立交橋

本文檔中包含的數據來自www.openstreetmap.org。數據在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"/> 

的代碼,我有尚未:

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 
+0

忘記包含我的python代碼的開始行(但很難確定如何正確格式化它,輸入時出錯了):import xml.etree.cElementTree as ET tree = ET.parse('target.osm ') root = tree.getroot() – Karlchen9 2014-09-29 11:59:00

+0

感謝管理員加入到原始問題 - 一個確實在這裏得到寵愛。 – Karlchen9 2014-09-29 16:53:03

回答

1

您需要遍歷每個節點的所有兒童,並與k="name"屬性搜索元素:

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

或使用您的get()方法:

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

注意,與節點一個名稱不一定代表OSM中的一個城市。相反,一個城市會有額外的標籤,如place=*

+0

第一種方法就像一種魅力 - 我所關注的一切。似乎「說謝謝」在這裏是政治上不正確的,所以我只欠你一個......歡呼! – Karlchen9 2014-09-29 16:36:39

0

你可能要考慮到充分利用現有的一個的OP-API wrapper

如果你不這樣做,你想使用SAX XML接口的性能。因此,您將創建一個解析器類並註冊XML子元素的回調。

相關問題