简体   繁体   English

从XML文件创建KML文件

[英]Creating a KML file from a XML file

How can I create KML files from the XML files using python. 如何使用python从XML文件创建KML文件。 I have a lot of XML files. 我有很多XML文件。 I have already parsed the data from the XML files using the SAX parser. 我已经使用SAX解析器解析了XML文件中的数据。

Now I want to create KML files from the data that I have parsed. 现在我想根据我解析的数据创建KML文件。

Is there any other way apart from xml.dom.minidom to write the KML file. 除了xml.dom.minidom之外还有其他方法可以编写KML文件。 I am currently thinking of creating a template KML file. 我目前正在考虑创建一个模板KML文件。 Then copying the template KML file and filling the 'data' in it. 然后复制模板KML文件并填写其中的“数据”。

Can anybody suggest a better way ? 任何人都可以提出更好的方法吗?

My main concern is Maintainability (writing the data using minidom is pretty confusing for somebody to read). 我主要担心的是可维护性(使用minidom编写数据对于有人阅读而言非常混乱)。

Try xml.etree.ElementTree . 试试xml.etree.ElementTree Here's a short example creating a couple of points in a KML file: 这是一个在KML文件中创建几个点的简短示例:

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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