我希望能够获取一个包含每个要素类的记录以及一些元数据字段(如摘要、描述等)的 excel 文件,并将其转换为要素类元数据。从我所做的研究来看,我似乎需要将 excel 表中的每条记录转换为 xml,然后从那里我可以将 xml 文件作为元数据导入。看起来我可以使用 ElementTree,但我有点不确定如何执行。有没有人这样做过,如果有,你能提供一些指导吗?
1 回答
伙计,这可能是一个过程!前几天我不得不为工作中的一个项目更新一些元数据信息,所以这里什么都没有。将所有元数据信息存储在 excel 表中作为字典列表或您选择的其他数据结构会很有帮助(我使用 csvs 并出于经验原因尝试远离 excel 电子表格)。
metaInfo = [{"featureClass":"fc1",
"abstract":"text goes here",
"description":"text goes here",
"tags":["tag1","tag2","tag3"]},
{"featureClass":"fc2",
"abstract":"text goes here",
"description":"text goes here",
"tags":["tag1","tag2","tag3"]},...]
从那里,我实际上会使用导出元数据功能导出当前元数据要素类,以使用 FGDC 模式将要素类元数据转换为 xml 文件。下面是一个代码示例:
#Directory containing ArcGIS Install files
installDir = arcpy.GetInstallInfo("desktop")["InstallDir"]
#Path to XML schema for FGDC
translator = os.path.join(installDir, "Metadata/Translator/ARCGIS2FGDC.xml")
#Export your metadata
arcpy.ExportMetadata_conversion(featureClassPath, translator, tempXmlExportPath)
从那里,您可以使用 xml 模块来访问 ElementTree 类。但是,我建议使用 lxml 模块(http://lxml.de/index.html#download),因为如果您需要特殊元素(如元数据中的换行符),它允许您通过 CDATA 工厂将 html 代码合并到元数据中. 从那里开始,假设您已经导入了 lxml,解析您的本地 xml 文档:
import lxml.etree as ET
tree = ET.parse(tempXmlExportPath)
root = tree.getroot()
如果要更新标签,请使用以下代码:
idinfo = root[0]
#Create keyworks element
keywords = ET.SubElement(idinfo, "keywords")
tree.write(tempXmlExportPath)
#Create theme child
theme = ET.SubElement(keywords, "theme")
tree.write(tempXmlExportPath)
#Create themekt and themekey grandchildren/insert tag info
themekt = ET.SubElement(theme, "themekt")
tree.write(tempXmlExportPath)
for tag in tags: #tags list from your dictionary
themekey = ET.SubElement(theme, "themekey")
themekey.text = tag
tree.write(tempXmlExportPath)
要更新摘要标签,请使用以下代码:
#Create descript tag
descript = ET.SubElement(idinfo, "descript")
tree.write(tempXmlExportPath)
#Create purpose child from abstract
abstract = ET.SubElement(descript, "abstract")
text = #get abstract string from dictionary
abstract.text = text
tree.write(tempXmlExportPath)
如果 xml 中的标签已经存在,则使用 parent.find("child") 方法将该标签存储为对象,并更新文本,类似于上面的代码示例。更新本地 xml 文件后,使用导入元数据方法将 xml 文件重新导入要素类并删除本地 xml 文件。
arcpy.ImportMetadata_conversion(tempXmlExportPath, "FROM_FGDC", featureClassPath)
shutil.rmtree(tempXmlExportPath)
请记住,Arc 中的这些工具仅适用于 32 位,因此如果您通过 64 位后台地理处理器编写脚本,这将不起作用。我正在使用 ArcMap 10.1。如果您有任何问题,请告诉我或查阅以下文档:
lxml 模块 http://lxml.de/index.html#documentation
导出元数据 arcpy http://resources.arcgis.com/en/help/main/10.1/index.html#//00120000000t000000
导入元数据 arcpy http://resources.arcgis.com/en/help/main/10.1/index.html#//00120000000w000000