[Solved] Python xml help? Finish my program?


You create a root element using ET.Element(), adding the children you want to it. Then, you give that as the root to an ET.ElementTree, and call .write() on that, setting xml_declaration to 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!')

0

solved Python xml help? Finish my program?