首页 > 解决方案 > how to replace XML values with values from a list

问题描述

I am trying to update start times in an XML file with new start times from a list in python. This is a sample of the XML (There are 9 orders in the list)

    <ppr:Group name="Order lists">
        <ppr:ProductionProgram ppr:id="1">
         <ppr:name>firmOrders</ppr:name>
         <ppr:Order ppr:id="1|19077013">
            <ppr:number>M742019552</ppr:number>
            <ppr:startTime>2019-10-28T06:45:00</ppr:startTime>
            <ppr:property name="Line code" value="G" metadata="true" />
            <ppr:modelRef refBy="pprId">M1|19077013</ppr:modelRef>
         </ppr:Order>

I have a list of the new start times

    newtimes = ['2020-03-16T08:00:02', '2020-03-16T08:00:03'] ect...

I know how to get to the xml start time values using,

    for x in productionprogram.iter('{http://ManHub.PPRData}startTime'):
        x.text = 

just not sure what to set it = to... something that replaces the values with 'newtimes' in order

Thanks!

标签: pythonxmllistindexing

解决方案


Your question isn't so much about how to "replace XML values" then it's about how to "keep track" of how many times you've iterated inside of a loop.

What you want is enumerate().

Let's try it out with a simple example.

I have a file containing the days of the weeks and their names called week.xml:

<week>
    <day>
        <name>Monday</name>
    </day>
    <day>
        <name>Tuesday</name>
    </day>
    <day>
        <name>Wednesday</name>
    </day>
    <day>
        <name>Thursday</name>
    </day>
    <day>
        <name>Friday</name>
    </day>
    <day>
        <name>Saturday</name>
    </day>
    <day>
        <name>Sunday</name>
    </day>
</week>

Let's replace their names using a list of values:

import xml.etree.ElementTree as ET
tree = ET.parse('week.xml')
root = tree.getroot()

short_days = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN']
for idx, day in enumerate(root.findall("day")):
    day.find("name").text = short_days[idx]

tree.write("short_week.xml")

And here is the new file called short_week.xml:

<week>
    <day>
        <name>MON</name>
    </day>
    <day>
        <name>TUE</name>
    </day>
    <day>
        <name>WED</name>
    </day>
    <day>
        <name>THU</name>
    </day>
    <day>
        <name>FRI</name>
    </day>
    <day>
        <name>SAT</name>
    </day>
    <day>
        <name>SUN</name>
    </day>
</week>

推荐阅读