Removing a Node from a DOM Tree


from xml.dom import minidom xmldoc = minidom.parse('stations.xml') doc_root = xmldoc.documentElement doc_root.removeChild(doc_root.childNodes[0])

The simplest way to remove a node from a DOM tree is to delete it using a direct reference. The first step is to parse the XML document using the minidom.parse(file) function to create a DOM tree document object.

After you have created the document objects, you retrieve the root of the document elements by accessing the documentElement attribute of the document object. To remove an object from the root of the document, use the removeChild(node). The removeChild function removes the nodes and any child nodes from the document.

The child nodes can be referenced directly by using the childNodes attribute of the root or node object. The childNodes attribute is a list, so individual elements can be accessed by their index number as shown in xml_removenode.py.

from xml.dom import minidom #Parse XML file to DOM tree xmldoc = minidom.parse('stations.xml') doc_root = xmldoc.documentElement print "\nNodes\n===================" nodeList = xmldoc.childNodes for node in nodeList:     print node.toprettyxml() #Delete first node doc_root.removeChild(doc_root.childNodes[0]) print "\nNodes\n===================" nodeList = xmldoc.childNodes for node in nodeList:     print node.toprettyxml()


xml_removenode.py

Nodes =================== <Workstations>     <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> </Workstations> Nodes =================== <Workstations>     <Computer>         <Processor>             Pentium Core 2         </Processor>         <Memory>             1024MB         </Memory>     </Computer>     <Computer>         <Processor>             Pentium Core Duo         </Processor>         <Memory>             1024MB         </Memory>     </Computer> </Workstations>


Output from xml_removenode.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