我需要帮助完成一个将值写入xml的python程序。在过去的几个月里学习了基本的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!')
带(#)的行需要完成。
我尝试了几种不同的在线方式,但它们不起作用,我不明白为什么。
如果有人能提供帮助,我们将不胜感激。
答案 0 :(得分:0)
使用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!')