从使用python创建的xml中删除的代码
我正在使用python复制并更新一个元数据xml文件——除了删除原始图元文件中的以下代码外,这一切都很好从使用python创建的xml中删除的代码,python,xml,Python,Xml,我正在使用python复制并更新一个元数据xml文件——除了删除原始图元文件中的以下代码外,这一切都很好 <?xml version="1.0" encoding="utf-8"?><?xml-stylesheet type='text/xsl' href='ANZMeta.xsl'?> 它需要在文件的开头 PHP中的答案是@,但我需要Python的解决方案 代码和完整的解释都在我原来的帖子里,但我把这个问题分开了,因为它不同于我原来的问题 谢谢 完整代码 impo
<?xml version="1.0" encoding="utf-8"?><?xml-stylesheet type='text/xsl' href='ANZMeta.xsl'?>
它需要在文件的开头
PHP中的答案是@,但我需要Python的解决方案
代码和完整的解释都在我原来的帖子里,但我把这个问题分开了,因为它不同于我原来的问题
谢谢
完整代码
import os, xml, arcpy, shutil, datetime, Tkinter, tkFileDialog, tkSimpleDialog
from xml.etree import ElementTree as et
path=os.getcwd()
RootDirectory=path
currentPath=path
arcpy.env.workspace = path
Count=0
DECLARATION = """<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type='text/xsl' href='ANZMeta.xsl'?>\n"""
Generated_XMLs=RootDirectory+'\GeneratedXML_LOG.txt'
f = open(Generated_XMLs, 'a')
f.write("Log of Metadata Creation Process - Update: "+str(datetime.datetime.now())+"\n")
f.close()
for root, dirs, files in os.walk(RootDirectory, topdown=False):
#print root, dirs
for directory in dirs:
try:
currentPath=os.path.join(root,directory)
except:
pass
os.chdir(currentPath)
arcpy.env.workspace = currentPath
print currentPath
#def Create_xml(currentPath):
FileList = arcpy.ListFeatureClasses()
zone="_Zone"
for File in FileList:
Count+=1
FileDesc_obj = arcpy.Describe(File)
FileNm=FileDesc_obj.file
check_meta=os.listdir(currentPath)
existingXML=FileNm[:FileNm.find('.')]
existingExtension=FileNm[FileNm.find('.'):]
print "XML: "+existingXML
#print check_meta
#if existingXML+'.xml' in check_meta:
#newMetaFile='new'
for f in check_meta:
if f.startswith(existingXML) and f.endswith('.xml'):
print "exists, file name:", f
newMetaFile=FileNm+"_2012Metadata.xml"
try:
shutil.copy2(f, newMetaFile)
except:
pass
break
else:
#print "Does not exist"
newMetaFile=FileNm+"_BaseMetadata.xml"
print "New meta file: "+newMetaFile+ " for: "+File
if newMetaFile.endswith('_BaseMetadata.xml'):
print "calling tkinter"
root = Tkinter.Tk()
root.withdraw()
file = tkFileDialog.askopenfile(parent=root,mode='rb',title='Choose a xml base file to match with: '+File)
if file != None:
metafile=os.path.abspath(file.name)
file.close()
#print metafile
shutil.copy2(metafile,newMetaFile)
print "copied"+metafile
root.destroy
else:
shutil.copy2('L:\Data_Admin\QA\Metadata_python_toolset\Master_Metadata.xml', newMetaFile)
#root = Tkinter.Tk()
#root.withdraw()
#newTitle=tkSimpleDialog.askstring('title', 'prompt')
#root.destroy
#print newTitle
print "Parsing meta file: "+newMetaFile
tree=et.parse(newMetaFile)
print "Processing: "+str(File)
for node in tree.findall('.//title'):
node.text = str(FileNm)
for node in tree.findall('.//procstep/srcused'):
node.text = str(currentPath+"\\"+existingXML+".xml")
dt=dt=str(datetime.datetime.now())
for node in tree.findall('.//procstep/date'):
node.text = str(dt[:10])
for node in tree.findall('.//procstep/time'):
node.text = str(dt[11:13]+dt[16:19])
for node in tree.findall('.//metd/date'):
node.text = str(dt[:10])
for node in tree.findall('.//northbc'):
node.text = str(FileDesc_obj.extent.YMax)
for node in tree.findall('.//southbc'):
node.text = str(FileDesc_obj.extent.YMin)
for node in tree.findall('.//westbc'):
node.text = str(FileDesc_obj.extent.XMin)
for node in tree.findall('.//eastbc'):
node.text = str(FileDesc_obj.extent.XMax)
for node in tree.findall('.//native/nondig/formname'):
node.text = str(os.getcwd()+"\\"+File)
for node in tree.findall('.//native/digform/formname'):
node.text = str(FileDesc_obj.featureType)
for node in tree.findall('.//avlform/nondig/formname'):
node.text = str(FileDesc_obj.extension)
for node in tree.findall('.//avlform/digform/formname'):
node.text = str(float(os.path.getsize(File))/int(1024))+" KB"
for node in tree.findall('.//theme'):
node.text = str(FileDesc_obj.spatialReference.name +" ; EPSG: "+str(FileDesc_obj.spatialReference.factoryCode))
print node.text
projection_info=[]
Zone=FileDesc_obj.spatialReference.name
if "GCS" in str(FileDesc_obj.spatialReference.name):
projection_info=[FileDesc_obj.spatialReference.GCSName, FileDesc_obj.spatialReference.angularUnitName, FileDesc_obj.spatialReference.datumName, FileDesc_obj.spatialReference.spheroidName]
print "Geographic Coordinate system"
else:
projection_info=[FileDesc_obj.spatialReference.datumName, FileDesc_obj.spatialReference.spheroidName, FileDesc_obj.spatialReference.angularUnitName, Zone[Zone.rfind(zone)-3:]]
print "Projected Coordinate system"
x=0
for node in tree.findall('.//spdom'):
for node2 in node.findall('.//keyword'):
#print node2.text
node2.text = str(projection_info[x])
#print node2.text
x=x+1
tree.write(newMetaFile)
with open(newMetaFile, 'w') as output: # would be better to write to temp file and rename
output.write(DECLARATION)
tree.write(output, xml_declaration=False, encoding='utf-8')
# xml_declaration=False - don't write default declaration
f = open(Generated_XMLs, 'a')
f.write(str(Count)+": "+File+"; "+newMetaFile+"; "+currentPath+";"+existingXML+"\n")
f.close()
# Create_xml(currentPath)
导入操作系统、xml、arcpy、shutil、datetime、Tkinter、tkFileDialog、tkSimpleDialog
从xml.etree导入ElementTree作为et
path=os.getcwd()
RootDirectory=path
当前路径=路径
arcpy.env.workspace=路径
计数=0
声明=”“”
\n“
Generated_XMLs=RootDirectory+'\GeneratedXML_LOG.txt'
f=开放(生成的“a”)
f、 写入(“元数据创建过程日志-更新:”+str(datetime.datetime.now())+“\n”)
f、 关闭()
对于os.walk(RootDirectory,top-down=False)中的root、dirs和文件:
#打印根目录
对于目录中的目录:
尝试:
currentPath=os.path.join(根目录)
除:
通过
os.chdir(当前路径)
arcpy.env.workspace=当前路径
打印当前路径
#def Create_xml(当前路径):
FileList=arcpy.ListFeatureClasses()
zone=“\u zone”
对于文件列表中的文件:
计数+=1
FileDesc_obj=arcpy.descripe(文件)
FileNm=FileDesc_obj.file
检查\u meta=os.listdir(当前路径)
existingXML=FileNm[:FileNm.find('.')]
existingExtension=FileNm[FileNm.find('.'):]
打印“XML:+existingXML
#打印支票
#如果check_meta中存在xml+“.xml”:
#newMetaFile='new'
对于check_meta中的f:
如果f.startswith(existingXML)和f.endswith('.xml'):
打印“存在,文件名:”,f
newMetaFile=FileNm+“_2012Metadata.xml”
尝试:
copy2(f,newMetaFile)
除:
通过
打破
其他:
#打印“不存在”
newMetaFile=FileNm+“\u BaseMetadata.xml”
打印“+文件”的“新图元文件”+“新图元文件+”
如果newMetaFile.endswith(“\u BaseMetadata.xml”):
打印“呼叫tkinter”
root=Tkinter.Tk()
root.draw()
file=tkFileDialog.askopenfile(parent=root,mode='rb',title='选择要与之匹配的xml基文件:'+file)
如果文件!=无:
metafile=os.path.abspath(file.name)
file.close()文件
#打印图元文件
copy2(元文件,新元文件)
打印“复制的”+图元文件
毁灭
其他:
copy2('L:\Data\u Admin\QA\Metadata\u python\u toolset\Master\u Metadata.xml',newMetaFile)
#root=Tkinter.Tk()
#root.draw()
#newTitle=tkSimpleDialog.askstring('title','prompt')
#毁灭
#打印新标题
打印“分析元文件:”+newMetaFile
tree=et.parse(newMetaFile)
打印“处理:”+str(文件)
对于tree.findall('.//title')中的节点:
node.text=str(FileNm)
对于tree.findall('.//procstep/srcused')中的节点:
node.text=str(currentPath+“\\”+现有xml+“.xml”)
dt=dt=str(datetime.datetime.now())
对于tree.findall('.//procstep/date')中的节点:
node.text=str(dt[:10])
对于tree.findall('.//procstep/time')中的节点:
node.text=str(dt[11:13]+dt[16:19])
对于tree.findall('.//metd/date')中的节点:
node.text=str(dt[:10])
对于tree.findall('.//northbc')中的节点:
node.text=str(FileDesc_obj.extent.YMax)
对于tree.findall('.//southbc')中的节点:
node.text=str(FileDesc_obj.extent.YMin)
对于tree.findall('.//westbc')中的节点:
node.text=str(FileDesc_obj.extent.XMin)
对于tree.findall('.//eastbc')中的节点:
node.text=str(FileDesc_obj.extent.XMax)
对于tree.findall('.//native/nondig/formname')中的节点:
node.text=str(os.getcwd()+“\\”+文件)
对于tree.findall('.//native/digform/formname')中的节点:
node.text=str(FileDesc_obj.featureType)
对于tree.findall('.//avlform/nondig/formname')中的节点:
node.text=str(FileDesc_obj.extension)
对于tree.findall('.//avlform/digform/formname')中的节点:
node.text=str(float(os.path.getsize(文件))/int(1024))+“KB”
对于tree.findall(“.//主题”)中的节点:
node.text=str(FileDesc_obj.spacealreference.name+“EPSG:”+str(FileDesc_obj.spacealreference.factoryCode))
打印node.text
投影信息=[]
Zone=FileDesc_obj.spatialReference.name
如果str中的“GCS”(FileDesc_obj.spacealreference.name):
projection_info=[FileDesc_obj.spatialReference.GCSName,FileDesc_obj.spatialReference.angularUnitName,FileDesc_obj.spatialReference.datumName,FileDesc_obj.spatialReference.spheroidName]
打印“地理坐标系”
其他:
projection_info=[FileDesc_obj.spatialReference.datumName,FileDesc_obj.spatialReference.spheroidName,FileDesc_obj.spatialReference.angularUnitName,分区[Zone.rfind(Zone)-3:]
打印“投影坐标系”
x=0
对于tree.findall('.//spdom')中的节点:
对于node.findall(“.//关键字”)中的node2:
#打印节点
import xml.etree.ElementTree as ET
# Build your XML document as normal...
root = ET.Element('root')
# Create 'fake' root node
fake_root = ET.Element(None)
# Add desired processing instructions. Repeat as necessary.
pi = ET.PI("xml-stylesheet", "type='text/xsl' href='ANZMeta.xsl'")
pi.tail = "\n"
fake_root.append(pi)
# Add real root as last child of fake root
fake_root.append(root)
# Write to file, using ElementTree.write( ) to generate <?xml ...?> tag.
tree = ET.ElementTree(fake_root)
tree.write("doc.xml", xml_declaration=True)
<?xml version='1.0' encoding='us-ascii'?>
<?xml-stylesheet type='text/xsl' href='ANZMeta.xsl'?>
<root />