Create XML file with python by iterating over lists

北城以北 提交于 2019-12-04 15:26:44
Carlos V

You need to do two things:

  • Move the lines Eli suggested into the for loop.
  • Remove the line: results.append(result) from the for loop. The SubElement factory takes as its first argument a parent element (as you know) and it appends the newly created instance to that parent. Therefore you don't need to append it again (you won't get any error, but you will get a different set of results than the ones you specified).

You loop should then look like:

for s in students:    
    for a in range(len(assignments)):

        result = ET.SubElement(results,"result")
        student = ET.SubElement(result,"student")
        assignment = ET.SubElement(result,"assignment")
        score = ET.SubElement(result,"score")

        student.text = str(s)
        assignment.text = str(assignments[a])
        score.text = str(scores[a])

You need to move these lines

result = ET.SubElement(results,"result")
student = ET.SubElement(result,"student")
assignment = ET.SubElement(result,"assignment")
score = ET.SubElement(result,"score")

To inside the for loop. Otherwise you're just adding the same result over and over again.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!