Changes between Version 20 and Version 21 of BluePrint/GIS/ShapefileLayers


Ignore:
Timestamp:
04/28/13 10:18:19 (9 years ago)
Author:
jonathlt
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • BluePrint/GIS/ShapefileLayers

    v20 v21  
    2828Alternatively, to use Python bindings, you could perform the import using GDAL which would allow more control over the import directly within Python, but should still handle the import into Postgres.
    2929
     30
     31{{{
     32'''
     33Dump the contents of a shapefile to an lxml etree object
     34Assumes the shapefile is encoded in UTF-8 format
     35Tested with TM_WORLD_BORDERS-0.3.shp
     36'''
     37import sys
     38import ogr
     39import os
     40
     41from lxml import etree
     42
     43if len(sys.argv) != 2:
     44    print "Usage: importshape.py filename"
     45    sys.exit(0)
     46   
     47shapefilename = sys.argv[1]
     48
     49layername = os.path.splitext(os.path.basename(shapefilename))[0]
     50
     51#Create the datasource
     52ds = ogr.Open( shapefilename )
     53
     54#Open the shapefile
     55if ds is None:
     56    print "Open failed.\n"
     57    sys.exit(0)
     58   
     59#Get the layer and iterate through the features
     60lyr = ds.GetLayer(0)
     61
     62root = etree.Element("shapefile",name=layername)
     63
     64for feat in lyr:
     65       
     66    featurenode = etree.SubElement(root,"feature")
     67   
     68    feat_defn = lyr.GetLayerDefn()
     69               
     70    for i in range(feat_defn.GetFieldCount()):
     71               
     72        field_defn = feat_defn.GetFieldDefn(i)
     73                       
     74        fieldnode = etree.SubElement(featurenode,field_defn.GetName())
     75               
     76        if field_defn.GetType() == ogr.OFTInteger:
     77            fieldnode.text = str(feat.GetFieldAsInteger(i))
     78
     79        elif field_defn.GetType() == ogr.OFTReal:
     80            fieldnode.text = str(feat.GetFieldAsDouble(i))
     81
     82        elif field_defn.GetType() == ogr.OFTString:
     83            FieldString = str(feat.GetFieldAsString(i))
     84            fieldnode.text = FieldString.decode(encoding='UTF-8',errors='strict')
     85           
     86    wktnode = etree.SubElement(featurenode,"wkt")
     87       
     88    geom = feat.GetGeometryRef()       
     89    wktnode.text = geom.ExportToWkt()   
     90               
     91
     92#Test the etree object
     93xmlString = etree.tostring(root, pretty_print=True)
     94f = open("test.xml","w")
     95f.write(xmlString)
     96
     97}}}
     98
     99
    30100----
    31101[wiki:BluePrint/GIS GIS BluePrints]ic