简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM