使用Python提取元数据XML文件,从Python脚本填充各种元素,然后将XML文件保存回其源代码。有一个名为“citeinfo”的现有元素,我正在尝试在其中创建两个子元素,一个称为“pubdate”,另一个称为“othercit”。当我运行脚本时,我没有得到任何错误,但是当我打开XML后处理时,我得到了第二个“引文”元素组,它是“citeinfo”的父元素,并且是我所有新元素的一行。这是我的Python:
import arcpy, sys
from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import Element, SubElement
import xml.etree.ElementTree as ET
from arcpy import env
env.overwriteOutput = True
fcpath = r"...\HL Metadata to BR Sample Data.gdb\NCI20102014_Oral"
translatorpath = r"...\Translator\ARCGIS2FGDC.xml"
xmlfile = r"...\Extras\FullMetaFC.xml"
arcpy.ExportMetadata_conversion(fcpath, translatorpath, xmlfile)
tree = ElementTree()
tree.parse(xmlfile)
a = tree.find('idinfo')
aa = tree.find('metainfo')
aaa = tree.find('eainfo')
b = ET.SubElement(a, 'citation')
c = ET.SubElement(b, 'citeinfo')
bb = ET.SubElement(c, 'pubdate')
d = ET.SubElement(c, 'othercit')
e = ET.SubElement(a, 'descript')
f = ET.SubElement(e, 'abstract')
g = ET.SubElement(e, 'purpose')
title = tree.find("idinfo/citation/citeinfo/title")
public_date = tree.find("idinfo/citation/citeinfo/pubdate")
cit_source = tree.find("idinfo/citation/citeinfo/othercit")
abstract = tree.find("idinfo/descript/abstract")
purpose = tree.find("idinfo/descript/purpose")
title.text = "Oral Cancer Incidence by County"
bb.text = "99990088"
d.text = "https://statecancerprofiles.cancer.gov/"
abstract.text = "Incidence rates are..."
purpose.text = "The State Cancer Profiles..."
tree.write(xmlfile)
arcpy.ImportMetadata_conversion(xmlfile, "FROM_FGDC", fcpath, "ENABLED")
以下是XML:
<citation>
<citeinfo>
<origin>X</origin>
<title>META_TESTING</title>
<geoform>vector digital data</geoform>
<pubdate>20102010</pubdate><othercit>www.google.com</othercit></citeinfo>
</citation>
我希望“引文”组看起来像:
<citation>
<citeinfo>
<title>National Cancer Institute, Oral Cancer Incidence by County</title>
<geoform>vector digital data</geoform>
<pubdate>20120510</pubdate>
<othercit>www.google.com</othercit>
</citeinfo>
</citation>
我将创建一个小助手函数来确保元素的存在。如果它存在,它返回它-如果它不存在,它创建它。你知道吗
现在你可以做:
注意,您可以在一行代码中
ET.parse()
一个文件。你知道吗简而言之,我们可以:
要漂亮地打印ElementTree文档,可以使用以下功能:
相关问题 更多 >
编程相关推荐