使用 Python 在 XML 中查找和替换值 [英] Find and Replace Values in XML using Python
问题描述
我希望使用 python 编辑 XML 文件.我想查找和替换标签中的关键字.过去,一位同事设置了模板 XML 文件,并使用查找和替换"程序来替换这些关键字.我想使用 python 来查找和替换这些关键字的值.我一直在自学 Elementtree 模块,但在尝试查找和替换时遇到了麻烦.我附上了我的 XML 文件的一小部分.你会看到一些用 % 包围的变量(即 %SITEDESCR%)这些是我想要替换的词,然后将 XML 保存到一个新文件中.任何帮助或建议都会很棒.
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.
谢谢,迈克
<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>
推荐答案
基础知识:
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.
这篇关于使用 Python 在 XML 中查找和替换值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!