Adding a Node to a DOM Tree : DOM « XML « Python Tutorial






from xml.dom import minidom

Station1 = ['Pentium M', '512MB']
Station2 = ['Pentium Core 2', '1024MB']
Station3 = ['Pentium Core Duo', '1024MB']
StationList = [Station1, Station2, Station3]

DOMimpl = minidom.getDOMImplementation()

xmldoc = DOMimpl.createDocument(None,"Workstations", None)
doc_root = xmldoc.documentElement

for station in StationList:
    #Create Node
    node = xmldoc.createElement("Computer")

    element = xmldoc.createElement('Processor')
    element.appendChild(xmldoc.createTextNode(station[0]))
    node.appendChild(element)

    element = xmldoc.createElement('Memory')
    element.appendChild(xmldoc.createTextNode(station[1]))
    node.appendChild(element)

    doc_root.appendChild(node)

nodeList = doc_root.childNodes
for node in nodeList:
    print node.toprettyxml()

file = open("stations.xml", 'w')
file.write(xmldoc.toxml())








20.2.DOM
20.2.1.Processing XML
20.2.2.Accessing Child Nodes
20.2.3.Accessing Element Attributes
20.2.4.Adding a Node to a DOM Tree
20.2.5.Removing a Node from a DOM Tree
20.2.6.Parsing XML
20.2.7.Getting Child Nodes
20.2.8.toxml Works on Any Node
20.2.9.Child Nodes Can Be Text
20.2.10.All the Way to Text
20.2.11.Searching for XML Elements
20.2.12.Every Element Is Searchable
20.2.13.Searching Is Actually Recursive
20.2.14.Parsing XML from a File
20.2.15.Parsing XML from a URL
20.2.16.Parsing XML from a String
20.2.17.Class Names of Parsed XML Objects
20.2.18.Generating XML with DOM
20.2.19.Parsing Sample with DOM
20.2.20.Tree Generation with DOM