0

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

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.