I'm trying to write a name in the list of a dictionary to XML file but I'm getting IndexError as child index out of range. I'm new to XML file. Here is my code
import os
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element, SubElement, Comment, tostring
from xml.dom import minidom
name = [{'vehicle': 'honda'}, {'vehicle': 'hyundai'}, {'vehicle': 'mercedes'}, {'vehicle': 'rangerover'}, {'vehicle': 'bentley'}, {'vehicle': 'toyota'}, {'vehicle': 'mecerati'}, {'vehicle': 'lamborgini'}]
l = [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (1, 0), (1, 2)]
for step in range(10):
i,j = l[step]
print(i,j)
name1 = str(name[i]['vehicle'])
root = Element('annotation')
folder = SubElement(root, 'folder')
folder.text="testing"
filename=SubElement(root, 'filename')
filename.text="1.jpg"
path=SubElement(root, 'path')
path.text="path"
source=SubElement(root, 'source')
obj=SubElement(root, 'object')
name=SubElement(obj,'name')
name.text=str(name1)
tree = ET.ElementTree(root)
tree.write(os.path.join('testing',str(step)+".xml"))
When second iteration occurs with the same i value it throws the error.
0 1
0 2
---> 10 name1 = str(name[i]['vehicle'])
IndexError: child index out of range
can you help me to figure out what wrong I'm doing and a way to fix it? I found a similar question but it didn't fix my error Child index out of range, python element tree
In your for loop you do name=SubElement(obj,'name')
, you are overwriting your original name list. Change that variable name to something else.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.