def printKML(doc, outfile): schema_ogc = Schema("ogckml22.xsd") schema_ogc.assertValid(doc) f = open(outfile, "w") f.write(etree.tostring(doc, pretty_print=True)) f.close()
def test_basic_kml_document_2(self): """Tests the creation of a basic OGC KML document.""" doc = KML.kml( KML.Document( KML.name("KmlFile"), KML.Placemark( KML.name("Untitled Placemark"), KML.Point( KML.coordinates("-95.265,38.959,0") ) ) ) ) # validate against a local schema self.assertTrue(Schema("ogckml22.xsd").validate(doc)) # validate against a remote schema self.assertTrue(Schema("http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd").validate(doc)) self.assertEquals( etree.tostring(doc), '<kml xmlns:gx="http://www.google.com/kml/ext/2.2" ' 'xmlns:atom="http://www.w3.org/2005/Atom" ' 'xmlns="http://www.opengis.net/kml/2.2">' '<Document>' '<name>KmlFile</name>' '<Placemark>' '<name>Untitled Placemark</name>' '<Point>' '<coordinates>-95.265,38.959,0</coordinates>' '</Point>' '</Placemark>' '</Document>' '</kml>' )
def load_kml_string(kml_string, schema_type = "kml22gx.xsd"): schema_gx = Schema(schema_type) doc = parser.fromstring(kml_string, schema_gx) if (schema_gx.validate(doc)): return doc else: print "Invalid kml format for string passed in" return None
def test_trivial_kml_document(self): """Tests the creation of a trivial OGC KML document.""" doc = KML.kml() schema = Schema("ogckml22.xsd") self.assertTrue(schema.validate(doc)) self.assertEquals( etree.tostring(doc), '<kml xmlns:gx="http://www.google.com/kml/ext/2.2" ' 'xmlns:atom="http://www.w3.org/2005/Atom" ' 'xmlns="http://www.opengis.net/kml/2.2"/>')
def load_kml_file(filename, schema_type = "kml22gx.xsd"): with open(filename) as fh: schema_gx = Schema(schema_type) doc = parser.parse(fh) if (schema_gx.validate(doc)): return doc.getroot() else: print "Invalid kml format for file: "+str(filename) return None
def test_trivial_kml_document(self): """Tests the creation of a trivial OGC KML document.""" doc = KML.kml() schema = Schema("ogckml22.xsd") self.assertTrue(schema.validate(doc)) self.assertEquals( etree.tostring(doc), '<kml xmlns:gx="http://www.google.com/kml/ext/2.2" ' 'xmlns:atom="http://www.w3.org/2005/Atom" ' 'xmlns="http://www.opengis.net/kml/2.2"/>' )
def test_trivial_kml_document(self): """Tests the creation of a trivial OGC KML document.""" doc = KML.kml() schema = Schema('ogckml22.xsd') self.assertTrue(schema.validate(doc)) data = etree.tostring(doc, encoding='ascii') expected = \ b'<kml xmlns:gx="http://www.google.com/kml/ext/2.2" ' \ b'xmlns:atom="http://www.w3.org/2005/Atom" ' \ b'xmlns="http://www.opengis.net/kml/2.2"/>' self.assertXmlEquivalentOutputs(data, expected)
def schema_invalid(file): 'Check if it is a valid schema' with open(file, 'r') as f: #The files supplied are most likely part of the google extension schema, so validate it against that root = parser.fromstring(f.read()) #Put the read cursor back at the start of the file f.seek(0) schema_gx = Schema("kml22gx.xsd") #If the kml file does not use a valid schema if not schema_gx.validate(root): return True else: return False
def test_parse_kml_file_with_cdata(self): "Tests the parsing of a local KML file, with a CDATA description string" test_datafile = path.join( path.dirname(__file__), 'testfiles', 'google_kml_tutorial/using_the_cdata_element.kml' ) # parse with validation with open(test_datafile) as f: doc = parse(f, schema=Schema('kml22gx.xsd')) self.assertEquals( etree.tostring(doc), '<kml xmlns="http://www.opengis.net/kml/2.2">' '<Document>' '<Placemark>' '<name>CDATA example</name>' '<description>' '<![CDATA[\n' ' <h1>CDATA Tags are useful!</h1>\n' ' <p><font color="red">Text is <i>more readable</i> and \n' ' <b>easier to write</b> when you can avoid using entity \n' ' references.</font></p>\n' ' ]]>' '</description>' '<Point>' '<coordinates>102.595626,14.996729</coordinates>' '</Point>' '</Placemark>' '</Document>' '</kml>' )
def test_set_max_decimal_places_track(self): """Tests setting the number of decimal places for track data""" from pykml.helpers import set_max_decimal_places test_kml = ('<?xml version="1.0" encoding="UTF-8"?>' '<kml xmlns="http://www.opengis.net/kml/2.2" ' 'xmlns:gx="http://www.google.com/kml/ext/2.2">' '<Folder>' '<Placemark>' '<gx:Track>' '<when>2010-05-28T02:02:09Z</when>' '<when>2010-05-28T02:02:35Z</when>' '<when>2010-05-28T02:02:44Z</when>' '<gx:coord>-122.111111 37.111111 151.333333</gx:coord>' '<gx:coord>-122.222222 37.222222 152.222222</gx:coord>' '<gx:coord>-122.333333 37.333333 153.333333</gx:coord>' '</gx:Track>' '</Placemark>' '</Folder>' '</kml>') doc = fromstring(test_kml, schema=Schema("kml22gx.xsd")) set_max_decimal_places(doc, max_decimals={ 'longitude': 3, 'latitude': 2, 'altitude': 1, }) coords_list = doc.findall( ".//{http://www.google.com/kml/ext/2.2}coord") #import ipdb; ipdb.set_trace() self.assertEquals(coords_list[0], '-122.111 37.11 151.3')
def test_fromstring_kml_document(self): "Tests the parsing of an valid KML string" test_kml = '<kml xmlns="http://www.opengis.net/kml/2.2"/>' tree = fromstring(test_kml, schema=Schema("ogckml22.xsd")) self.assertEquals(etree.tostring(tree), test_kml) tree = fromstring(test_kml) self.assertEquals(etree.tostring(tree), test_kml)
def test_kml_document_with_atom_element(self): """Tests the creation of a KML document with an ATOM element.""" doc = KML.kml( KML.Document( ATOM.author(ATOM.name("J. K. Rowling")), ATOM.link(href="http://www.harrypotter.com"), KML.Placemark(KML.name("Hogwarts"), KML.Point(KML.coordinates("1,1"))))) self.assertTrue(Schema("kml22gx.xsd").validate(doc)) target = etree.fromstring( '<kml ' 'xmlns:atom="http://www.w3.org/2005/Atom" ' 'xmlns:gx="http://www.google.com/kml/ext/2.2" ' 'xmlns="http://www.opengis.net/kml/2.2">' '<Document>' '<atom:author>' '<atom:name>J. K. Rowling</atom:name>' '</atom:author>' '<atom:link href="http://www.harrypotter.com"/>' '<Placemark>' '<name>Hogwarts</name>' '<Point>' '<coordinates>1,1</coordinates>' '</Point>' '</Placemark>' '</Document>' '</kml>') self.assertTrue(compare_xml(target, doc))
def test_basic_kml_document(self): """Tests the creation of a basic KML with Google Extensions .""" doc = KML.kml( GX.Tour( GX.Playlist( GX.SoundCue( KML.href("http://dev.keyhole.com/codesite/cntowerfacts.mp3") ), GX.Wait( GX.duration(10) ), GX.FlyTo( GX.duration(5), GX.flyToMode("bounce"), KML.LookAt( KML.longitude(-79.387), KML.latitude(43.643), KML.altitude(0), KML.heading(-172.3), KML.tilt(10), KML.range(1200), KML.altitudeMode("relativeToGround"), ) ) ) ) ) self.assertTrue(Schema("kml22gx.xsd").validate(doc)) self.assertEqual( etree.tostring(doc).decode(), '<kml ' 'xmlns:atom="http://www.w3.org/2005/Atom" ' 'xmlns:gx="http://www.google.com/kml/ext/2.2" ' 'xmlns="http://www.opengis.net/kml/2.2">' '<gx:Tour>' '<gx:Playlist>' '<gx:SoundCue>' '<href>http://dev.keyhole.com/codesite/cntowerfacts.mp3</href>' '</gx:SoundCue>' '<gx:Wait>' '<gx:duration>10</gx:duration>' '</gx:Wait>' '<gx:FlyTo>' '<gx:duration>5</gx:duration>' '<gx:flyToMode>bounce</gx:flyToMode>' '<LookAt>' '<longitude>-79.387</longitude>' '<latitude>43.643</latitude>' '<altitude>0</altitude>' '<heading>-172.3</heading>' '<tilt>10</tilt>' '<range>1200</range>' '<altitudeMode>relativeToGround</altitudeMode>' '</LookAt>' '</gx:FlyTo>' '</gx:Playlist>' '</gx:Tour>' '</kml>' )
def test_parse_kml_file(self): "Tests the parsing of a local KML file, with validation" test_datafile = path.join( path.dirname(__file__), 'testfiles', 'google_kml_developers_guide/complete_tour_example.kml' ) # parse without validation with open(test_datafile) as f: doc = parse(f) # parse with validation (local schema file) with open(test_datafile) as f: doc = parse(f, schema=Schema('kml22gx.xsd')) # parse with validation (remote schema file) with open(test_datafile) as f: doc = parse(f, schema=Schema('http://code.google.com/apis/kml/schema/kml22gx.xsd')) self.assertTrue(True)
def writeFile(doc, suff, folder): doc.Document.append(folder) ofile = file(__file__.rstrip('.py') + suff + '.kml', 'w') ofile.write(etree.tostring(doc, pretty_print=True)) try: assert (Schema("kml22gx.xsd").validate(doc)) except AssertionError, e: print "AssertionError on " + suff + " file" pass
def test_parse_kml_document(self): "Tests the parsing of an valid KML file object" test_kml = '<kml xmlns="http://www.opengis.net/kml/2.2"/>' fileobject = StringIO(test_kml) schema = Schema("ogckml22.xsd") tree = parse(fileobject, schema=schema) self.assertEquals(etree.tostring(tree), test_kml) tree = parse(fileobject, schema=schema) self.assertEquals(etree.tostring(tree), test_kml)
def test_parse_invalid_kml_document(self): "Tests the parsing of an invalid KML document" fileobject = StringIO('<bad_element />') try: tree = parse(fileobject, schema=Schema("ogckml22.xsd")) self.assertTrue(False) except etree.XMLSyntaxError: self.assertTrue(True) except: self.assertTrue(False)
def test_fromstring_invalid_kml_document(self): "Tests the parsing of an invalid KML string" test_kml = '<bad_element />' try: tree = fromstring(test_kml, schema=Schema("ogckml22.xsd")) self.assertTrue(False) except etree.XMLSyntaxError: self.assertTrue(True) except: self.assertTrue(False)
def validate_kml(filepath, schema = "https://developers.google.com/kml/schema/kml21.xsd"): """ Validates kml located at filepath. TODO: Even imported kml files do not validate against default xml """ schema_gomaps = Schema(schema) data = "" with open(filepath, "r") as temp: data = temp.read() assert(data != "") doc = parser.fromstring(data) return schema_ogc.assertValid(doc)
def test_parse_kml_url_2(self): "Tests the parsing of a KML URL" url = 'http://code.google.com/apis/kml/documentation/kmlfiles/animatedupdate_example.kml' fileobject = urllib2.urlopen(url) tree = parse(fileobject, schema=Schema('kml22gx.xsd')) self.assertEquals( etree.tostring(tree)[:137], '<kml xmlns="http://www.opengis.net/kml/2.2" ' 'xmlns:gx="http://www.google.com/kml/ext/2.2">' '<Document>' '<name>gx:AnimatedUpdate example</name>' )
def test_parse_invalid_ogc_kml_document(self): """Tests the parsing of an invalid KML document. Note that this KML document uses elements that are not in the OGC KML spec. """ url = 'http://code.google.com/apis/kml/documentation/kmlfiles/altitudemode_reference.kml' fileobject = urllib2.urlopen(url) try: tree = parse(fileobject, schema=Schema("ogckml22.xsd")) self.assertTrue(False) except etree.XMLSyntaxError: self.assertTrue(True) except: self.assertTrue(False)
def test_parse_kml_url(self): "Tests the parsing of a KML URL" url = 'http://code.google.com/apis/kml/documentation/kmlfiles/altitudemode_reference.kml' fileobject = urllib2.urlopen(url) tree = parse(fileobject, schema=Schema('kml22gx.xsd')) self.assertEquals( etree.tostring(tree)[:185], '<kml xmlns="http://www.opengis.net/kml/2.2" ' 'xmlns:gx="http://www.google.com/kml/ext/2.2">' '<!-- required when using gx-prefixed elements -->' '<Placemark>' '<name>gx:altitudeMode Example</name>' )
def task_to_kml_with_pykml(df_task, outdir, filename_base, disp): from lxml import etree from pykml.parser import Schema from pykml.factory import KML_ElementMaker as KML from pykml.factory import GX_ElementMaker as GX s_coords = task_to_string(df_task) (lat, lon) = calculate_center(df_task) #def turn_point_to_placemark(tp): # placemark = KML.Placemark( # KML.name(tp['Name']), # KML.description(tp['Name']), # KML.Point( # KML.coordinates(tp['Lon'], tp['Lat'], tp['Altitude']) # ), # ) # return(placemark) #placemarks = [turn_point_to_placemark(tp) for i, tp in df_task.iterrows()] doc = KML.kml( KML.Placemark( KML.name("Condor task '%s'" % filename_base), KML.LookAt( KML.longitude(lon), KML.latitude(lat), KML.heading(0), KML.tilt(60), KML.range(80000), GX.altitudeMode("relativeToSeaFloor"), #GX.altitudeMode("absolute"), ), KML.LineString( KML.extrude(1), GX.altitudeMode("relativeToSeaFloor"), #GX.altitudeMode("absolute"), KML.coordinates(s_coords), ), ), #*placemarks ) if disp: print(etree.tostring(doc, pretty_print=True)) # output a KML file (named based on the Python script) filename_out = os.path.join(outdir, filename_base + '.kml') print("Output '%s'" % filename_out) outfile = file(filename_out, 'w') outfile.write(etree.tostring(doc, pretty_print=True)) assert Schema('kml22gx.xsd').validate(doc)
def main(argv=None): if argv is None: argv = sys.argv try: try: opts, args = getopt.getopt(argv[1:], "h", ["help"]) except getopt.error, msg: raise Usage(msg) # main code schema = Schema("kml22gx.xsd") filename = argv[1] with open(filename) as f: kmldoc = parse(f, schema=schema) print(write_python_script_for_kml_document(kmldoc))
def test_parse_kml_url(self): "Tests the parsing of a KML URL" url = 'http://code.google.com/apis/kml/documentation/KML_Samples.kml' #url = 'http://kml-samples.googlecode.com/svn/trunk/kml/Document/doc-with-id.kml' #url = 'http://code.google.com/apis/kml/documentation/kmlfiles/altitudemode_reference.kml' #url = 'http://code.google.com/apis/kml/documentation/kmlfiles/animatedupdate_example.kml' fileobject = urllib2.urlopen(url) tree = parse(fileobject, schema=Schema("ogckml22.xsd")) self.assertEquals( etree.tostring(tree)[:78], '<kml xmlns="http://www.opengis.net/kml/2.2">' '<Document>' '<name>KML Samples</name>' )
def test_parse_kml_url_2(self): "Tests the parsing of a KML URL" url = 'http://code.google.com/apis/kml/documentation/kmlfiles/animatedupdate_example.kml' try: fileobject = urllib.request.urlopen(url) tree = parse(fileobject, schema=Schema('kml22gx.xsd')) self.assertEqual( etree.tostring(tree)[:137], '<kml xmlns="http://www.opengis.net/kml/2.2" ' 'xmlns:gx="http://www.google.com/kml/ext/2.2">' '<Document>' '<name>gx:AnimatedUpdate example</name>') except urllib.error.URLError: print('Unable to access the URL. Skipping test...')
def validate_file(file): schema_ogc = Schema("ogckml22.xsd") schema_gx = Schema("kml22gx.xsd") if schema_ogc.validate(doc): print("Fichier ogc") elif schema_gx.validate(doc): print("Fichier gx") else: print("Erreur format fichier")
def test_count_elements(self): """Tests the counting of elements in a KML document.""" from pykml.util import count_elements test_datafile = path.join( path.dirname(__file__), 'testfiles', 'google_kml_developers_guide/complete_tour_example.kml') with open(test_datafile) as f: doc = parse(f, schema=Schema('kml22gx.xsd')) summary = count_elements(doc) self.assertTrue(summary.has_key('http://www.opengis.net/kml/2.2')) self.assertEqual( 4, summary['http://www.opengis.net/kml/2.2']['Placemark']) self.assertTrue(summary.has_key('http://www.google.com/kml/ext/2.2')) self.assertEqual(5, summary['http://www.google.com/kml/ext/2.2']['FlyTo']) self.assertEqual(2, summary['http://www.google.com/kml/ext/2.2']['Wait'])
def test_write_python_script_for_kml_document_with_comments(self): """Tests the creation of an OGC KML document with several comments""" import os import tempfile from pykml.parser import parse from pykml.factory import write_python_script_for_kml_document test_datafile = path.join( path.dirname(__file__), 'testfiles', 'simple_file_with_comments.kml' ) schema = Schema('kml22gx.xsd') with open(test_datafile) as f: doc = parse(f, schema=schema) script = write_python_script_for_kml_document(doc) # create a temporary python file handle, tfile = tempfile.mkstemp(suffix='.py') #print tfile # Useful for debugging with open(tfile, 'w') as f: f.write(script) # execute the temporary python file to create a KML file import subprocess current_env = os.environ.copy() current_env["PYTHONPATH"] = os.path.abspath( os.path.join(path.dirname(__file__),'../..') ) handle, temp_kml_file = tempfile.mkstemp(suffix='.kml') #print temp_kml_file # Useful for debugging with open(temp_kml_file, 'w') as f: exit_code = subprocess.call(["python",tfile], stdout=f, env=current_env) self.assertEqual(exit_code, 0) # parse and validate the KML generated by the temporary script doc2 = parse(temp_kml_file, schema=schema) # test that the root element is as expected self.assertEqual(doc2.docinfo.root_name, 'kml') # test that the original and generated documents are equivalent self.assertTrue(compare_etree(doc.getroot(), doc2.getroot()))
def test_write_python_script_for_kml_document_with_namespaces(self): """Tests the creation of an OGC KML document with several namespaces""" import os import tempfile from pykml.parser import parse from pykml.factory import write_python_script_for_kml_document test_datafile = path.join( path.dirname(__file__), 'testfiles', 'google_kml_developers_guide/complete_tour_example.kml' ) schema = Schema('kml22gx.xsd') with open(test_datafile) as f: doc = parse(f, schema=schema) script = write_python_script_for_kml_document(doc) # create a temporary python file handle, tfile = tempfile.mkstemp(suffix='.py') #print tfile #uncomment to print the temporary filename with open(tfile, 'w') as f: f.write(script) # execute the temporary python file to create a KML file # set the PYTHONPATH variable so that it references the root # of the pyKML library import subprocess current_env = os.environ.copy() current_env["PYTHONPATH"] = os.path.abspath( os.path.join(path.dirname(__file__),'../..') ) handle, temp_kml_file = tempfile.mkstemp(suffix='.kml') #print temp_kml_file with open(temp_kml_file, 'w') as f: exit_code = subprocess.call(["python",tfile], stdout=f, env=current_env) self.assertEqual(exit_code, 0) # parse and validate the KML generated by the temporary script doc2 = parse(temp_kml_file, schema=schema) # test that the root element is as expected self.assertEqual(doc2.docinfo.root_name, 'kml')
def test_write_python_script_for_kml_document_with_cdata(self): """Tests the creation of an OGC KML document with a cdata tag""" import os import tempfile from pykml.parser import parse from pykml.factory import write_python_script_for_kml_document test_datafile = path.join( path.dirname(__file__), 'testfiles', 'google_kml_tutorial/using_the_cdata_element.kml' ) file = 'test/testfiles/' schema = Schema('kml22gx.xsd') with open(test_datafile) as f: doc = parse(f, schema=schema) script = write_python_script_for_kml_document(doc) self.assertEquals( script, 'from lxml import etree\n' 'from pykml.factory import KML_ElementMaker as KML\n' 'from pykml.factory import ATOM_ElementMaker as ATOM\n' 'from pykml.factory import GX_ElementMaker as GX\n' '\n' 'doc = KML.kml(\n' ' KML.Document(\n' ' KML.Placemark(\n' ' KML.name(\'CDATA example\'),\n' ' KML.description(\n' ' \'<h1>CDATA Tags are useful!</h1> \'\n' ' \'<p><font color="red">Text is <i>more readable</i> and \'\n' ' \'<b>easier to write</b> when you can avoid using entity \'\n' ' \'references.</font></p> \'\n' ' ),\n' ' KML.Point(\n' ' KML.coordinates(\'102.595626,14.996729\'),\n' ' ),\n' ' ),\n' ' ),\n' ')\n' 'print etree.tostring(etree.ElementTree(doc),pretty_print=True)\n' ) # create a temporary python file handle, tfile = tempfile.mkstemp(suffix='.py') #print tfile with open(tfile, 'w') as f: f.write(script) # execute the temporary python file to create a KML file import subprocess current_env = os.environ.copy() current_env["PYTHONPATH"] = os.path.abspath( os.path.join(path.dirname(__file__),'../..') ) handle, temp_kml_file = tempfile.mkstemp(suffix='.kml') with open(temp_kml_file, 'w') as f: exit_code = subprocess.call( ["python",tfile], stdout=f, env=current_env ) self.assertEqual(exit_code, 0) # parse and validate the KML generated by the temporary script doc2 = parse(temp_kml_file, schema=schema) # test that the root element is as expected self.assertEqual(doc2.docinfo.root_name, 'kml')
doc.append(KML.Folder()) # read in a csv file, and create a placemark for each record url="http://earthquake.usgs.gov/earthquakes/catalogs/eqs7day-M2.5.txt" fileobject = urllib2.urlopen(url) for row in csv.DictReader(fileobject): timestamp = datetime.strptime(row["Datetime"], "%A, %B %d, %Y %H:%M:%S %Z") pm = KML.Placemark( KML.name("Magnitude={0}".format(row['Magnitude'])), KML.TimeStamp( KML.when(timestamp.strftime('%Y-%m-%dT%H:%M:%SZ')), ), KML.styleUrl( "#earthquake-style-{thresh}".format( thresh=int(float(row['Magnitude'])) ) ), makeExtendedDataElements(row), KML.Point( KML.coordinates("{0},{1}".format(row["Lon"],row["Lat"])) ) ) doc.Folder.append(pm) # check if the schema is valid from pykml.parser import Schema schema_gx = Schema("kml22gx.xsd") schema_gx.assertValid(doc) print etree.tostring(doc, pretty_print=True)
) doc.append(style3) pointFolder = KML.Folder() pointList = [] print "Creating KML" for y in range(len(points)): if(points[y][2] <=10): colorvalue = "red" elif(points[y][2] >10 and points[y][2] <=14): colorvalue = "yellow" else: colorvalue = "white" coord = points[y][1],points[y][0] pm = KML.Placemark( KML.name(points[y][2]), KML.styleUrl(colorvalue), KML.Point( KML.coordinates(str(coord).strip('() ')) ) ) pointFolder.append(pm) doc.append(pointFolder) schema_ogc = Schema("ogckml22.xsd") schema_ogc.assertValid(pointFolder) fout = open(str(args.outfile).strip('[]\''),'w') fout.write(etree.tostring(doc, pretty_print=True)) fout.close()
def main(): """ Create a KML document with a folder and a style for each earthquake magnitude """ doc = KML.Document() icon_styles = [ [2, 'ff000000'], [3, 'ffff0000'], [4, 'ff00ff55'], [5, 'ffff00aa'], [6, 'ff00ffff'], [7, 'ff0000ff'], ] # create a series of Icon Styles for threshold, color in icon_styles: doc.append( KML.Style( KML.IconStyle( KML.color(color), KML.scale(threshold / 2), KML.Icon( KML.href('http://maps.google.com/mapfiles/kml/shapes/earthquake.png'), ), KML.hotSpot(x='0.5', y='0', xunits='fraction', yunits='fraction'), ), get_balloon_style(), id='earthquake-style-{threshold}'.format(threshold=threshold), ) ) doc.append(KML.Folder()) # read in a csv file, and create a placemark for each record url = 'http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.csv' fileobject = urlopen(url) if six.PY3: # fileobject is bytes, csv requires string import codecs fileobject = codecs.getreader('utf-8')(fileobject) for row in csv.DictReader(fileobject): timestamp = datetime.strptime(row['time'], '%Y-%m-%dT%H:%M:%S.%fZ') pm = KML.Placemark( KML.name('Magnitude={0}'.format(row['mag'])), KML.TimeStamp( KML.when(timestamp.strftime('%Y-%m-%dT%H:%M:%SZ')), ), KML.styleUrl( '#earthquake-style-{thresh}'.format( thresh=int(float(row['mag'])) ) ), make_extended_data_elements(row), KML.Point( KML.coordinates('{0},{1}'.format(row['longitude'], row['latitude'])) ) ) doc.Folder.append(pm) # check if the schema is valid schema_gx = Schema('kml22gx.xsd') schema_gx.assertValid(doc) kml = KML.kml(doc) print(etree.tostring(format_xml_with_cdata(kml), pretty_print=True, encoding='utf-8', xml_declaration=True).decode())
def test_initialize_schema_remote_url(self): schema = Schema("http://code.google.com/apis/kml/schema/kml22gx.xsd") self.assertTrue(isinstance(schema.schema, etree.XMLSchema))
def test_initialize_schema(self): """Tests the creation Schema instance""" schema = Schema("ogckml22.xsd") self.assertTrue(isinstance(schema.schema, etree.XMLSchema))
from pykml.helpers import set_max_decimal_places import gpxpy import gpxpy.gpx from bs4 import BeautifulSoup as bs from tqdm import tqdm logging.basicConfig(level=logging.DEBUG) # parse kml root = parser.parse(sys.stdin).getroot() set_max_decimal_places(root, max_decimals={'longitude': 6, 'latitude': 6}) logging.info('kml22gx validation: %r', Schema('kml22gx.xsd').validate(root)) logging.info('ogckml22 validation: %r', Schema('ogckml22.xsd').validate(root)) # https://developer.mozilla.org/en-US/docs/Web/XPath/Functions # https://devhints.io/xpath placemarks = root.xpath('//k:Placemark', namespaces={'k': 'http://www.opengis.net/kml/2.2'}) logging.info(f'found {len(placemarks)} placemarks') # TODO read these fields from the kml file itself! # TODO make the mapping to their display names configurable # fields in KML file downloaded from FS fields = { 'RECAREANAM': 'Name: ',
), GX.AnimatedUpdate( GX.duration(5), KML.Update( KML.targetHref(), KML.Change( KML.IconStyle( KML.scale(10.0), targetId="mystyle" ) ) ) ), GX.Wait( GX.duration(5) ) ) ) ) ) print etree.tostring(doc, pretty_print=True) # output a KML file (named based on the Python script) outfile = file(__file__.rstrip('.py')+'.kml','w') outfile.write(etree.tostring(doc, pretty_print=True)) schema = Schema('kml22gx.xsd') import ipdb; ipdb.set_trace() schema.validate(doc)