简体   繁体   中英

Changing a specific xml element using Python 3 ElementTree

I have a set of metadata files in xml which are updated regularly and I'm trying to automate. I've worked out how to itteratively find and then replace text in the desired element of the xml but thought there must be a direct way to access and change the element. I just can't work it out.

The metadata xml is formatted:

<?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>

My iterative approach was:

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)

Ideas appreciated on a better way.

I would write to the file only once I'm done with the loop:

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)

I would even simplify that loop further to:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM