Revision 4 as of 2005-02-09 19:41:10

Clear message

Some notes on how to use xml.dom.minidom:

   1 from xml.dom.minidom import parse, parseString
   2 
   3 dom1 = parse( "foaf.rdf" )   # parse an XML file
   4 dom2 = parseString( "<myxml>Some data <empty/> some more data</myxml>" )

Then you can do things like:

   1 dir( dom2 ) # get a list of things to do
   2 
   3 print dom2.toxml() # prints out "<?xml version="1.0" ?>..."
   4 print dom2.nodeName # will return "#document"
   5 print dom2.firstChild.nodeName # will return "myxml" because it's <myxml>...
   6 print dom2.firstChild.nodeValue # it's None! (everything's in the children.)
   7 print dom2.firstChild.hasChildNodes() # it's True.
   8 print dom2.firstChild.firstChild.nodeName # will return "#text"
   9 print dom2.firstChild.firstChild.nodeValue # will return "Some data"
  10 print dom2.firstChild.firstChild.nextSibling.nodeName # will return "empty" because it's <empty/>
  11 print dom2.firstChild.firstChild.nextSibling.nodeValue # it's None!
  12 print dom2.firstChild.firstChild.nextSibling.nextSibling.nodeName # will return "#text"
  13 print dom2.firstChild.firstChild.nextSibling.nextSibling.nodeValue # will return " some mode data"

Examples of Use

Import a Node

You can use DOM 2 "importNode" to take part of one XML document, and put it into another XML document.

   1 from xml.dom.minidom import parse
   2 dom1 = parse("foo.xml")
   3 dom2 = parse("bar.xml")
   4 x = dom1.importNode(dom2.childNodes[1],  # take 2nd node in "bar.xml"
   5                     True)  # deep copy
   6 dom1.childNodes[1].appendNode(x)  # append to children of 2nd node in "foo.xml"
   7 print dom1.toxml()

Unable to edit the page? See the FrontPage for instructions.