【问题标题】:Parsing a kml file using lxml使用 lxml 解析 kml 文件
【发布时间】:2015-11-09 16:23:37
【问题描述】:

我有一个 KML 文件 - 我使用 wikipedia 'default' 作为示例:

<?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>

我正在尝试提取坐标。

现在,我有一个嵌入名称空间的 sn-p 工作:

#!/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'

我认为这意味着我的“发现”在这种情况下没有找到任何东西。

我在这里缺少什么?

【问题讨论】:

    标签: python xml python-3.x lxml


    【解决方案1】:

    这段代码,

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

    不返回任何内容,因为没有使用前缀。见http://lxml.de/xpathxslt.html#namespaces-and-prefixes

    以下是两个可行的选项。

    1. 定义另一个以真实前缀为键的nsmap:

      nsmap2 = {"k": root.nsmap[None]}
      print (root.find('.//k:coordinates', nsmap2).text)
      
    2. 不要为前缀而烦恼。将命名空间 URI 放在大括号内(“Clark notation”)以形成通用元素名称:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多