如何在python中使用ElementTree编写带有多个根元素的xml文件

时间:2017-07-23 05:04:21

标签: python xml elementtree

我有python脚本,我已经编写了使用xml.etree.cElementTree编写xml文件的逻辑,逻辑如下所示

import xml.etree.cElementTree as ET

root = ET.Element("root")
for I in range(0,10):
    ET.SubElement(root, "field1").text = "some value1"
    ET.SubElement(root, "field2").text = "some vlaue2"

tree = ET.ElementTree(root)
tree.write("filename.xml")

并提供类似

的输出
<root>
      <field1>some value1</field1>
      <field2>some value2</field2>
      <field1>some value1</field1>
      <field2>some value2</field2>
      <field1>some value1</field1>
      <field2>some value2</field2>
      <field1>some value1</field1>
      <field2>some value2</field2>......
</root>

但是我想添加多个root并需要像下面那样输出

<root>
  <field1>some value1</field1>
  <field2>some value2</field2>
</root>
<root>
  <field1>some value1</field1>
  <field2>some value2</field2>
</root>
<root>
  <field1>some value1</field1>
  <field2>some value2</field2>
</root>
<root>
  <field1>some value1</field1>
  <field2>some value2</field2>
</root>

是否可以使用python

中的xml.etree.cElementTree来编写上述文件

1 个答案:

答案 0 :(得分:1)

您要生成的内容不是有效的xml。 有关详细信息,请参阅Do you always have to have a root node with xml/xsd?

此外,您始终可以手动连接字符串。

import xml.etree.cElementTree as ET
result= ''
for I in range(0, 10):
    root = ET.Element("root")
    ET.SubElement(root, "field1").text = "some value1"
    ET.SubElement(root, "field2").text = "some vlaue2"
    result += ET.tostring(root)
print(result) # or write the result to a file