Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

Find and Replace Values in XML using Python

I am looking to edit XML files using python. I want to find and replace keywords in the tags. In the past, a co-worker had set up template XML files and used a "find and replace" program to replace these key words. I want to use python to find and replace these key words with values. I have been teaching myself the Elementtree module, but I am having trouble trying to do a find and replace. I have attached a snid-bit of my XML file. You will seen some variables surrounded by % (ie %SITEDESCR%) These are the words I want to replace and then save the XML to a new file. Any help or suggestions would be great.

Thanks, Mike

<metadata>
<idinfo>
<citation>
<citeinfo>
 <origin>My Company</origin>
 <pubdate>05/04/2009</pubdate>
 <title>POLYGONS</title>
 <geoform>vector digital data</geoform>
 <onlink>\C$ArcGISDevelopmentGeodatabasePDA_STD_05_25_2009.gdb</onlink>
</citeinfo>
</citation>
 <descript>
 <abstract>This dataset represents the mapped polygons developed from the field data for the %SITEDESCR%.</abstract>
 <purpose>This dataset was created to accompany some stuff.</purpose>
 </descript>
<timeperd>
<timeinfo>
<rngdates>
 <begdate>%begdate%</begdate>
 <begtime>unknown</begtime>
 <enddate>%enddate%</enddate>
 <endtime>unknown</endtime>
 </rngdates>
 </timeinfo>
 <current>ground condition</current>
 </timeperd>
question from:https://stackoverflow.com/questions/6523886/find-and-replace-values-in-xml-using-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The basics:

from xml.etree import ElementTree as et
tree = et.parse(datafile)
tree.find('idinfo/timeperd/timeinfo/rngdates/begdate').text = '1/1/2011'
tree.find('idinfo/timeperd/timeinfo/rngdates/enddate').text = '1/1/2011'
tree.write(datafile)

You can shorten the path if the tag name is unique. This syntax finds the first node at any depth level in the tree.

tree.find('.//begdate').text = '1/1/2011'
tree.find('.//enddate').text = '1/1/2011'

Also, read the documentation, esp. the XPath support for locating nodes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...