Adding a Node to a DOM Tree


from xml.dom import minidom DOMimpl = minidom.getDOMImplementation() xmldoc = DOMimpl.createDocument(None, "Workstations", None) doc_root = xmldoc.documentElement node = xmldoc.createElement("Computer") doc_root.appendChild(node)

Adding child nodes to a DOM tree can be managed in several different ways. This phrase discusses using the xml.dom.minidom module provided with Python to create a DOM tree and add nodes to it.

The first step is to create a DOM object by calling the minidom.getDOMImplementation() function, which returns a DOMImplementation object. Then call the createDocument(qualifiedName, publicId, systemId) function of the DOMImplementation object to create the XML document. The createDocument function returns a Document object.

Once you have created the Document object, create nodes using the createElement(tagName) function of the Document object. The createElement function of the Docmuent object returns a node object.

After you have created child nodes, the DOM tree can be constructed using the appendChild(node) function to add node objects as child nodes of other node objects. Once the tree has been constructed, add the tree to the Document object using the appendChild(node) function of the Document object to attach the topmost level of the tree.

from xml.dom import minidom Station1 = ['Pentium M', '512MB'] Station2 = ['Pentium Core 2', '1024MB'] Station3 = ['Pentium Core Duo', '1024MB'] StationList = [Station1, Station2, Station3] #Create DOM object DOMimpl = minidom.getDOMImplementation() #Create Document xmldoc = DOMimpl.createDocument(None, "Workstations", None) doc_root = xmldoc.documentElement #Add Nodes 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)     #Add Node     doc_root.appendChild(node) print "\nNodes\n===================" nodeList = doc_root.childNodes for node in nodeList:     print node.toprettyxml() #Write the document file = open("stations.xml", 'w') file.write(xmldoc.toxml())


xml_addnode.py

Nodes =================== <Computer>     <Processor>         Pentium M     </Processor>     <Memory>         512MB     </Memory> </Computer> <Computer>     <Processor>         Pentium Core 2     </Processor>     <Memory>         1024MB     </Memory> </Computer> <Computer>     <Processor>         Pentium Core Duo     </Processor>     <Memory>         1024MB     </Memory> </Computer>


Output from xml_addnode.py code.



Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net