简体   繁体   中英

Creating a KML file from a XML file

How can I create KML files from the XML files using python. I have a lot of XML files. I have already parsed the data from the XML files using the SAX parser.

Now I want to create KML files from the data that I have parsed.

Is there any other way apart from xml.dom.minidom to write the KML file. I am currently thinking of creating a template KML file. Then copying the template KML file and filling the 'data' in it.

Can anybody suggest a better way ?

My main concern is Maintainability (writing the data using minidom is pretty confusing for somebody to read).

Try xml.etree.ElementTree . Here's a short example creating a couple of points in a KML file:

from xml.etree import ElementTree as et

class Kml(object):
    def __init__(self):
        self.root = et.Element('kml')
        self.doc = et.SubElement(self.root,'Document')

    def add_placemark(self,name,desc,lat,long,alt):
        pm = et.SubElement(self.doc,'Placemark')
        et.SubElement(pm,'name').text = name
        et.SubElement(pm,'description').text = desc
        pt = et.SubElement(pm,'Point')
        et.SubElement(pt,'coordinates').text = '{},{},{}'.format(lat,long,alt)

    def write(self,filename):
        tree = et.ElementTree(self.root)
        tree.write(filename)

kml = Kml()
kml.add_placemark('Location1','Description1',-120,45,0)
kml.add_placemark('Location2','Description2',60,-45,0)
kml.write('out.kml')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM