I have a existing xml file as following:
<vehicleTravelTimeMeasurements>
<vehicleTravelTimeMeasurement name="ckkkkkkkkkk" no="2">
<start link="1" pos="3.864983"/>
<end link="3" pos="23.275375"/>
</vehicleTravelTimeMeasurement>
<vehicleTravelTimeMeasurement name="" no="3">
<start link="1" pos="3.864983"/>
<end link="2" pos="13.275375"/>
</vehicleTravelTimeMeasurement>
</vehicleTravelTimeMeasurements>
I am trying to construct the same format as shown above by using xml.etree.cElementTree, and add them into the xml correctly:
new = ET.Element("vehicleTravelTimeMeasurement", name = "kkk", no = "4")
newsub1 = ET.Element("start", link = "1", pos="3.88888")
newsub2 = ET.Element("end",link = "3", pos = "3.88888")
could someone help me out with this?
Thank you in advance!
You wanted to use SubElement
and add the start
and end
elements to the vehicleTravelTimeMeasurement
element. Then insert that newly created element at position 2, since 0 and 1 are already occupied.
import xml.etree.ElementTree as ET
def indent(elem, level=0):
i = "\n" + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
xml = '''<vehicleTravelTimeMeasurements>
<vehicleTravelTimeMeasurement name="ckkkkkkkkkk" no="2">
<start link="1" pos="3.864983"/>
<end link="3" pos="23.275375"/>
</vehicleTravelTimeMeasurement>
<vehicleTravelTimeMeasurement name="" no="3">
<start link="1" pos="3.864983"/>
<end link="2" pos="13.275375"/>
</vehicleTravelTimeMeasurement>
</vehicleTravelTimeMeasurements>'''
root = ET.fromstring(xml)
new = ET.Element("vehicleTravelTimeMeasurement", name = "kkk", no = "4")
newsub1 = ET.SubElement(new, "start", link = "1", pos="3.88888")
newsub2 = ET.SubElement(new, "end",link = "3", pos = "3.88888")
root.insert(2, new)
indent(root)
with open('test.xml', 'w') as f:
f.write(ET.tostring(root))