Ghost
Ghost

Reputation: 450

Append new node into XML using python

I have written the below code to create moderately large XML file, wherein I will be creating nodes in loop.

import xml.etree.cElementTree as ET
number = 0

def xml_write(number,doc):
   ET.SubElement(doc, "extra-TextID", used="true").text = ""+str(number)  ##in each loop number will be changed from 0 to 9

while number != 10:
   doc = ET.Element("message")
   xml_write(number,doc)
   tree = ET.ElementTree(doc)
   tree.write('XML_file.xml')
   number = number + 1

But running the above code I am only getting the last node, i.e., with "9" in the last line. Data is getting replaced in the file. How to append it so that I will get all the nodes containing 0 to 9 in each node.

    <?xml version="1.0"?>
    -<message>
       <source>Rain</source>
       <translations language="Dev">Cyclone</translations>
       <extra-TextID used="true">9</extra-TextID>
     <message>

I need to get xml file as:

    <?xml version="1.0"?>
    -<message>
       <source>Rain</source>
       <translations language="Dev">Cyclone</translations>
       <extra-TextID used="true">0</extra-TextID>
     <message>
    <?xml version="1.0"?>
    -<message>
       <source>Rain</source>
       <translations language="Dev">Cyclone</translations>
       <extra-TextID used="true">1</extra-TextID>
     <message>
    <?xml version="1.0"?>
    -<message>
       <source>Rain</source>
       <translations language="Dev">Cyclone</translations>
       <extra-TextID used="true">3</extra-TextID>
     <message>
      .
      .
      .
    <?xml version="1.0"?>
    -<message>
       <source>Rain</source>
       <translations language="Dev">Cyclone</translations>
       <extra-TextID used="true">9</extra-TextID>
     <message>

Upvotes: 0

Views: 229

Answers (1)

alecxe
alecxe

Reputation: 474271

The ElementTree library would not dump an XML with multiple root elements. If you want to have this kind of output in the XML file, append the generated elements manually:

with open('XML_file.xml', 'wb') as f:
    while number != 10:
        doc = ET.Element("message")
        xml_write(number, doc)

        f.write(ET.tostring(doc, method="xml"))

        number += 1

Upvotes: 1

Related Questions