[Tutor] Generating XML using Python

Peter Otten __peter__ at web.de
Mon Apr 11 11:11:02 CEST 2011


tee chwee liong wrote:

> 
> sorry for lack of details. yes i would like to output in 1 xml file.
> i would like to generate port 1 and its details (link, speed etc) then
> move to second port, port 2 and generate its details (link, speed etc) tq

As I said, instead of creating a new root on every iteration, create it once 
before you enter the loop. Then write the tree after the loop has 
termininated:

import xml.etree.ElementTree as ET

lspeed=2
tspeed=3

root = ET.Element("Test")
for port in range(1,9):
    head = ET.SubElement(root, "Default_Config", Port=str(port))
    title = ET.SubElement(head, "LINK")
    title.text = str(lspeed)
    title = ET.SubElement(head, "Target_Speed")

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




More information about the Tutor mailing list