gpt4 book ai didi

python - 通过遍历列表用 python 创建 XML 文件

转载 作者:数据小太阳 更新时间:2023-10-29 02:26:55 27 4
gpt4 key购买 nike

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

最佳答案

你需要做两件事:

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

你的循环应该是这样的:

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

关于python - 通过遍历列表用 python 创建 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16681543/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com