Python Language Create and Build XML Documents


Import Element Tree module

import xml.etree.ElementTree as ET

Element() function is used to create XML elements


SubElement() function used to create sub-elements to a give element

c = ET.SubElement(p, 'child1')

dump() function is used to dump xml elements.

# Output will be like this
#<parent><child1 /></parent>

If you want to save to a file create a xml tree with ElementTree() function and to save to a file use write() method

tree = ET.ElementTree(p)

Comment() function is used to insert comments in xml file.

comment = ET.Comment('user comment')
p.append(comment) #this comment will be appended to parent element