Create a new XML file

    #Create new XML
    #root = ET.Element('MyRootNode')                  #Normal create
    attributes = {"ver": "1.0"}                            #If you want attributes added to the root node
    root = ET.Element('MyRootNode', attributes)

    #----- CREATE ALL THE LEVEL 1 NODES -----
    nodes_level1 = {}
    nodes_level1['Brightness'] = ET.SubElement(root, 'Brightness')
    nodes_level1['Colour'] = ET.SubElement(root, 'Colour')

    #----- CREATE THE BRIGHTNESS NODE CONTENT -----
    #Add data to one of the level 1 nodes
    nodes_level2 = []
    nodes_level2.append(ET.SubElement(nodes_level1['Brightness'], 'PointBlock'))
    #Add attributes to that node
    nodes_level2[len(nodes_level2)-1].set("xleft", "0.0")
    nodes_level2[len(nodes_level2)-1].set("xright", "32.0")
    
    #Add sub nodes to it
    nodes_level3 = []
    
    nodes_level3.append(ET.SubElement(nodes_level2[len(nodes_level2)-1], 'Point'))
    #Add attributes to that node
    nodes_level3[len(nodes_level3)-1].set("x", "0.0")
    nodes_level3[len(nodes_level3)-1].set("y", "0.0")
    nodes_level3[len(nodes_level3)-1].set("type", "1")

    nodes_level3.append(ET.SubElement(nodes_level2[len(nodes_level2)-1], 'Point'))
    #Add attributes to that node
    nodes_level3[len(nodes_level3)-1].set("x", "0.0")
    nodes_level3[len(nodes_level3)-1].set("y", "0.0")
    nodes_level3[len(nodes_level3)-1].set("type", "2")

    #All done, output the XML
    ET.indent(root, space=" ", level=0)         #Make the XML nice to read for humans (add indents and line breaks)
    data = ET.tostring(root, encoding='utf8').decode('utf8')
Output
<?xml version='1.0' encoding='utf8'?>
<MyRootNode ver="1.0">
 <Brightness>
  <PointBlock xleft="0.0" xright="32.0">
   <Point x="0.0" y="0.0" type="1" />
   <Point x="0.0" y="0.0" type="2" />
  </PointBlock>
 </Brightness>
 <Colour />
</MyRootNode>

Output modified XML as a string

  ET.indent(root, space=" ", level=0)         #Make the XML nice to read for humans (add indents and line breaks)
  data = ET.tostring(root, encoding='utf8').decode('utf8')
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published. Required fields are marked *