pythonxml-parsing

Find Placemarks in kml file


I want to find all the Placemarks in a kml file:

from lxml import etree
doc = etree.parse(filename)
for elem in doc.findall('<Placemark>'):
   print(elem.find("<Placemark>").text) 

This doesn't work, i.e. it doesn't find anything, I think because each Placemark is unique in that each has its own id, e.g.:

<Placemark id="ID_09795">
<Placemark id="ID_15356">
<Placemark id="ID_64532">

How do I do this?

Edit: changed code based on @ScottHunter comment:

placemark_list = doc.findall("Placemark")
print ("length:" + str(len(placemark_list)))
for placemark in placemark_list:
  print(placemark.text) 

length is 0


Solution

  • It's hard to tell without seeing the full file, but try something like this

    placemark_list = doc.xpath("//*[local-name()='Placemark']")
    print(len(placemark_list))
    

    and see if it works.