在kml文件中不匹配

在kml文件中不匹配

本文介绍了Python ElementTree find()在kml文件中不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试使用元素树从kml文件中查找元素,如下所示:

I'm trying to find an element from a kml file using element trees as follows:

from xml.etree.ElementTree import ElementTree

tree = ElementTree()
tree.parse("history-03-02-2012.kml")
p = tree.find(".//name")

文件的足够子集可以证明问题如下:

A sufficient subset of the file to demonstrate the problem follows:

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Document>
    <name>Location history from 03/03/2012 to 03/10/2012</name>
  </Document>
</kml>

存在名称元素;为什么搜索结果为空?

A "name" element exists; why does the search come back empty?

推荐答案

name 元素试图匹配实际上是在KML命名空间中,但您并不是在考虑该命名空间。

The name element you're trying to match is actually within the KML namespace, but you aren't searching with that namespace in mind.

尝试:

p = tree.find(".//{http://www.opengis.net/kml/2.2}name")

如果您使用的是lxml的XPath而不是标准库ElementTree,则可以将名称空间作为字典传递:

If you were using lxml's XPath instead of the standard-library ElementTree, you'd instead pass the namespace in as a dictionary:

>>> tree = lxml.etree.fromstring('''<kml xmlns="http://www.opengis.net/kml/2.2">
...   <Document>
...     <name>Location history from 03/03/2012 to 03/10/2012</name>
...   </Document>
... </kml>''')
>>> tree.xpath('//kml:name', namespaces={'kml': "http://www.opengis.net/kml/2.2"})
[<Element {http://www.opengis.net/kml/2.2}name at 0x23afe60>]

这篇关于Python ElementTree find()在kml文件中不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 04:25