使用arcpy写入XML(Arcview许可证)

时间:2012-08-09 13:33:40

标签: python xml arcgis

我需要生成一个功能的xml属性数据,但我只有Arcview许可证,所以我不能使用Export XML工具。我有什么选择?

由于

1 个答案:

答案 0 :(得分:1)

Python拥有标准库中已包含的所有内容。下面是在shapefile要素类上打开搜索标记并将选定字段及其值转储到xml元素的代码。完成所有行后,它会将顶部聚合元素转储到xml文件中。请注意我使用的是一个仅在10.1版本中可用的arcpy.da搜索标记,但是您可以轻松地修改代码以使用常规的arcpy搜索器(或者更新器件)。

#in some cases cElementTree won't be available, but it's lots faster,
#so get it if we can
try:
    import xml.etree.cElementTree as et
except ImportError:
    import xml.etree.ElementTree as et

import arcpy

def rows_as_dicts(cursor):
    '''
    Yields rows from passed Arcpy da cursor as dicts
    '''
    colnames = cursor.fields
    uc = hasattr(cursor, 'updateRow')
    for row in cursor:
        row_object = dict(zip(colnames, row))
        yield row_object
        if uc:
            cursor.updateRow([row_object[colname] for colname in colnames])

def dump2xml(row, stands, elelst):
    '''
    Builds the xml tree from the passed row dict
    '''

    # stand level creation
    stand = et.Element("stand")

    stand.set("tractid", row['TRACTID'])
    stand.set('stand', str(row['STAND']))

    # add field elements with their values
    for e in elelst:
        xele = et.SubElement(stand, e)
        xele.text = str(row[e])

    #add to top level stands element
    stands.append(stand)

def main():
    #establish top level element
    stands = et.Element("stands")

    #set fields to output to xml
    fields = ('MAPNAME ACRES TYP PROGRAM SI AGE YR').split()

    #get cursor going and make the xml elements
    fc = 'c:/arcview/sf/summerville/stand.shp'
    with arcpy.da.SearchCursor(fc, ['*']) as sc:
        for row in rows_as_dicts(sc):
            dump2xml(row, stands, fields)

    #throw the entire xml tree to a file        
    xmltree = et.ElementTree(stands)
    xmltree.write('c:/temp/stands.xml', encoding='UTF-8')

    return

if __name__ == '__main__':
    main()
祝你好运,

麦克