2015-11-09 96 views
1

我有一個KML文件KML文件 - 我使用的wikipedia 'default'作爲樣本:解析使用LXML

<?xml version="1.0" encoding="UTF-8"?> 
<kml xmlns="http://www.opengis.net/kml/2.2"> 
<Document> 
<Placemark> 
    <name>New York City</name> 
    <description>New York City</description> 
    <Point> 
    <coordinates>-74.006393,40.714172,0</coordinates> 
    </Point> 
</Placemark> 
</Document> 
</kml> 

而且我想提取的座標。

現在,我已經得到了嵌入的命名空間的一個片段工作搜索:

#!/usr/python/python3.4/bin/python3 

from lxml import etree as ET 

tree = ET.parse('sample.kml') 
root = tree.getroot 

print (root.find('.//{http://www.opengis.net/kml/2.2}coordinates').text) 

這工作得很好。

但是已經發現這一點:

Parsing XML with namespace in Python via 'ElementTree'

我試圖通過從文件中讀取的命名空間去做,用「root.nsmap」。

print (root.nsmap) 

給我:

{None: '{http://www.opengis.net/kml/2.2}'} 

所以我覺得我應該能夠做到這一點:

print (root.find('.//coordinates',root.nsmap).text) 

或者非常類似的東西,使用None命名空間。 (例如沒有前綴)。但是,這並不工作 - 我做的,當它得到一個錯誤:

AttributeError: 'NoneType' object has no attribute 'text' 

我認爲這意味着我在這種情況下「查找」沒有發現任何東西。

缺少什麼我在這裏?

回答

1

此代碼,

​​

,因爲不使用前綴不返回任何東西。見http://lxml.de/xpathxslt.html#namespaces-and-prefixes

下面是兩個選項的工作。

  1. 定義一個真正的前綴另一nsmap關鍵:

    nsmap2 = {"k": root.nsmap[None]} 
    print (root.find('.//k:coordinates', nsmap2).text) 
    
  2. 不要理會前綴。把花括號(「克拉克表示法」)中的命名空間URI,形成一個通用的元素名稱:

    ns = root.nsmap[None] 
    print (root.find('.//{{{0}}}coordinates'.format(ns)).text)