我需要生成要素属性数据的 xml,但我只有 Arcview 许可证,所以不能使用导出 XML 工具。我有哪些选择?
谢谢
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()
祝你好运,
麦克风