python - 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!
解决方案
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>
推荐阅读
- python - 在列表Python中搜索元素时返回列表值的键
- pandas - 熊猫,每 x 行取决于其他行的值
- tippyjs - 几秒钟后如何隐藏tippy js工具提示?
- c# - 为什么我必须调用两次初始化命令?(否则我得到输出“t@”)
- database - 索引 Ref 字段 Mongodb
- python - for循环内pickle上的内存泄漏导致内存错误
- javascript - 将数据从 dojo 屏幕传递到反应屏幕
- python - 如何在python中将一个句子分成两个句子?
- node.js - 我正在使用 JS 中的 axios 从网站请求 html 内容,但该网站阻止了我的请求
- c - 分段错误的不确定性