| 30 | |
| 31 | {{{ |
| 32 | ''' |
| 33 | Dump the contents of a shapefile to an lxml etree object |
| 34 | Assumes the shapefile is encoded in UTF-8 format |
| 35 | Tested with TM_WORLD_BORDERS-0.3.shp |
| 36 | ''' |
| 37 | import sys |
| 38 | import ogr |
| 39 | import os |
| 40 | |
| 41 | from lxml import etree |
| 42 | |
| 43 | if len(sys.argv) != 2: |
| 44 | print "Usage: importshape.py filename" |
| 45 | sys.exit(0) |
| 46 | |
| 47 | shapefilename = sys.argv[1] |
| 48 | |
| 49 | layername = os.path.splitext(os.path.basename(shapefilename))[0] |
| 50 | |
| 51 | #Create the datasource |
| 52 | ds = ogr.Open( shapefilename ) |
| 53 | |
| 54 | #Open the shapefile |
| 55 | if ds is None: |
| 56 | print "Open failed.\n" |
| 57 | sys.exit(0) |
| 58 | |
| 59 | #Get the layer and iterate through the features |
| 60 | lyr = ds.GetLayer(0) |
| 61 | |
| 62 | root = etree.Element("shapefile",name=layername) |
| 63 | |
| 64 | for 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 |
| 93 | xmlString = etree.tostring(root, pretty_print=True) |
| 94 | f = open("test.xml","w") |
| 95 | f.write(xmlString) |
| 96 | |
| 97 | }}} |
| 98 | |
| 99 | |