3

我正在尝试获取一个看起来像这样的 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 文件。我想不通的是如何使用相同的元素标签,但为每个标签分配不同的值。

4

2 回答 2

2

你需要移动这些行

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

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

于 2013-05-22T00:26:29.247 回答
2

你需要做两件事:

  • Eli建议的行移到 for 循环中。
  • results.append(result)从 for 循环中删除行: 。工厂将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])
于 2013-05-22T00:54:46.563 回答