How to write xml file with multiple root element using ElementTree in python

假如想象 提交于 2019-12-12 05:30:11

问题


I have python script and I have already written logic of writing xml file using xml.etree.cElementTree and the logic is look like below

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

and it give output like

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

but I want to add multiple root and need out put like below

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

is it possible to write like above file using xml.etree.cElementTree in python


回答1:


What you want to generate is not valid xml. See Do you always have to have a root node with xml/xsd? for more info.

Also you can always manually concatenate the string.

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


来源:https://stackoverflow.com/questions/45261681/how-to-write-xml-file-with-multiple-root-element-using-elementtree-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!