1

我在 xml 中有一组元数据文件,这些文件会定期更新,我正在尝试自动化。我已经研究出如何迭代地查找并替换所需 xml 元素中的文本,但认为必须有一种直接的方法来访问和更改元素。我就是搞不定。

元数据 xml 的格式为:

<?xml version="1.0" ?>
    <metadata xml:lang="en">
       <Esri>
          <CreaDate>20120405</CreaDate>
          <CreaTime>13113000</CreaTime>
          <ArcGISFormat>1.0</ArcGISFormat>
          <SyncOnce>TRUE</SyncOnce>
          <ModDate>20121129</ModDate>
          <ModTime>11433300</ModTime>
          <ArcGISProfile>ItemDescription</ArcGISProfile>
       </Esri>
       <dataIdInfo>
          <idPurp>Updated :: 121129_114038</idPurp>     
       </dataIdInfo>
    </metadata>

我的迭代方法是:

for child in root:
    for xel in child.iter('idPurp'):
        download_new_datetime = strftime('%y%m%d_%H%M%S')
        download_new_text = 'Downloaded :: '
        xel.text = download_new_text + download_new_datetime
        tree.write(xmlfile)

想法以更好的方式受到赞赏。

4

2 回答 2

0

只有在完成循环后,我才会写入文件:

import xml.etree.ElementTree as ET
from time import strftime

xmlfile = '/tmp/file'
tree = ET.parse(xmlfile)
root = tree.getroot()

for child in root:
    for xel in child.iter('idPurp'):
        download_new_datetime = strftime('%y%m%d_%H%M%S')
        download_new_text = 'Downloaded :: '
        xel.text = download_new_text + download_new_datetime

tree.write(xmlfile)

我什至会将该循环进一步简化为:

for child in root:
    for xel in child.iter('idPurp'):
        xel.text = 'Downloaded :: ' + time.strftime('%y%m%d_%H%M%S')
于 2012-12-26T20:53:38.543 回答
0

Two simpler ways, both work, tested.

First:

import xml.etree.ElementTree as ET
from time import strftime

xmlfile = 'metadata.xml'
tree = ET.parse(xmlfile)
root = tree.getroot()

xel = root.find('./dataIdInfo/idPurp')
xel.text = 'Downloaded :: ' + strftime('%y%m%d_%H%M%S')

tree.write(xmlfile)

Second:

import xml.etree.ElementTree as ET
from time import strftime

xmlfile = 'metadata.xml'
tree = ET.parse(xmlfile)
root = tree.getroot()

xel = root[1][0]
xel.text = 'Downloaded :: ' + strftime('%y%m%d_%H%M%S')

tree.write(xmlfile)

I prefer the first one, it's more readable in my opinion.

于 2018-07-01T14:44:40.617 回答