通过迭代列表,使用python创建XML文件

时间:2013-05-22 00:14:36

标签: python xml moodle

我正在尝试获取一个看起来像这样的xml文件,以便我可以将其导入moodle成绩簿:

<results>
  <result>
    <student>1</student>
    <assignment>100</assignment>
    <score>0</score>
  </result>
  <result>
    <student>1</student>
    <assignment>101</assignment>
    <score>4</score>
  </result>
  <result>
    <student>1</student>
    <assignment>102</assignment>
    <score>10</score>
  </result>
  <result>
    <student>2</student>
    <assignment>100</assignment>
    <score>0</score>
  </result>
  <result>
    <student>2</student>
    <assignment>101</assignment>
    <score>4</score>
  </result>
  <result>
    <student>2</student>
    <assignment>102</assignment>
    <score>10</score>
  </result>
</results>

我曾尝试在python中编写一些代码,在仔细阅读文档后,我能想到的最好的是:

import xml.etree.cElementTree as ET

students = [1,2]
assignments=[100,101,102]
scores=[0,4,10]
results = ET.Element("results")
result = ET.SubElement(results,"result")
student = ET.SubElement(result,"student")
assignment = ET.SubElement(result,"assignment")
score = ET.SubElement(result,"score")

for s in students:    
    for a in range(len(assignments)):
        student.text = str(s)
        assignment.text = str(assignments[a])
        score.text = str(scores[a])
        results.append(result)
tree = ET.ElementTree(results)
tree.write('test.xml')

这几乎给了我想要的东西,但最后一个条目似乎覆盖了所有以前的条目,如下所示:

<results>
  <result>
    <student>2</student>
    <assignment>102</assignment>
    <score>10</score>
  </result>
  <result>
    <student>2</student>
    <assignment>102</assignment>
    <score>10</score>
  </result>
  <result>
    <student>2</student>
    <assignment>102</assignment>
    <score>10</score>
  </result>
  <result>
    <student>2</student>
    <assignment>102</assignment>
    <score>10</score>
  </result>
  <result>
    <student>2</student>
    <assignment>102</assignment>
    <score>10</score>
  </result>
  <result>
    <student>2</student>
    <assignment>102</assignment>
    <score>10</score>
  </result>
  <result>
    <student>2</student>
    <assignment>102</assignment>
    <score>10</score>
  </result>
</results>

我试图找到一个解决方案,但似乎大多数问题只是编写一个包含不同元素的xml文件。我无法弄清楚的是如何使用相同的元素标签,但为每个标签分配不同的值。

2 个答案:

答案 0 :(得分:2)

您需要移动这些行

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

for循环内部。否则,您只是一遍又一遍地添加相同的result

答案 1 :(得分:2)

你需要做两件事:

  • 将建议的行Eli移至for循环中。
  • 从for循环中删除行results.append(result)SubElement工厂将第一个参数作为父元素 (如您所知)并且将新创建的实例附加到 家长。因此你不需要再次追加它(你不会得到它 任何错误,但你会得到一组不同的结果 你指定了。)。

你的循环应该如下:

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])