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