编程语言
首页 > 编程语言> > 通过遍历列表使用python创建XML文件

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

作者:互联网

我正在尝试获取一个看起来像这样的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文件而解决.我不知道如何使用相同的element标签,但如何为每个标签分配不同的值.

解决方法:

您需要做两件事:

>将建议的行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])

标签:moodle,xml,python
来源: https://codeday.me/bug/20191030/1971246.html