Python ElementTree find() not matching within kml file

不打扰是莪最后的温柔 提交于 2020-01-01 18:16:53

问题


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?


回答1:


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

Try:

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

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


来源:https://stackoverflow.com/questions/9639786/python-elementtree-find-not-matching-within-kml-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!