Python xml 帮忙?完成我的程序?

Python xml help? Finish my program?

我需要帮助来完成 python 程序,该程序将值写入 xml。在过去几个月学习了基本的 python 概念后,我不知所措,不确定如何继续。我花了最后几个小时进行研究,但一无所获。我的代码是:

import xml.etree.cElementTree as ET

#Initialize xml file

speed = 0
t = 0
acc = 0
dt = 5/60
print ('This program writes a set of values to an xml file.')
#output header to file
#output to file: t, acc, speed

while (speed < 100):
   acc = acc + 5
   speed = speed + acc*dt
   t = t + dt
   #Output to file: t, acc, speed
acc = 0
while (t <= 5):
   t = t + 1
   #Output to file: t, acc, speed
while (speed > 0):
   acc = acc - 5
   speed = speed + acc*dt
   t = t + dt
   #Output to file: t, acc, speed

#Close output file
print ('Program done!')

带 (#) 的行需要完成。

我尝试了几种在网上找到的不同方法,但它们都不起作用,我不明白为什么。

如果有人能提供帮助,将不胜感激。

您使用 ET.Element() 创建一个根元素,向其中添加您想要的子元素。然后,将其作为 ET.ElementTree 的根,并对其调用 .write(),将 xml_declaration 设置为 True

import xml.etree.cElementTree as ET


def record_time(root, time, speed, acc):
    attribs = {"t": str(time), "speed": str(speed), "acc": str(acc)}
    ET.SubElement(root, "record", attribs)

root = ET.Element("data")

speed = 0
t = 0
acc = 0
dt = 5/60
print ('This program writes a set of values to an xml file.')

#output to file: t, acc, speed
record_time(root, t, speed, acc)

while (speed < 100):
   acc = acc + 5
   speed = speed + acc*dt

   t = t + dt
   record_time(root, t, speed, acc)
acc = 0
while (t <= 5):
   t = t + 1
   record_time(root, t, speed, acc)
while (speed > 0):
   acc = acc - 5
   speed = speed + acc*dt
   t = t + dt
   record_time(root, t, speed, acc)

#The following lines automatically create, write and close your xml for you, with the appropriate XML header.
tree = ET.ElementTree(root)
tree.write("YOUR_FILENAME_HERE.xml", xml_declaration=True)

print ('Program done!')