'''NOTE''': Some people think that MiniDOM is a slow and very memory hungry DOM implementation. According to these people, if you are looking for a fast, memory efficient and simple to use tool for working with XML, try ElementTree instead (in the [[http://docs.python.org/library/xml.etree.elementtree.html | xml.etree]] package), or use the external [[http://lxml.de/ | lxml]] implementation. Some notes on how to use {{{xml.dom.minidom}}}: {{{ #!python from xml.dom.minidom import parse, parseString dom1 = parse( "foaf.rdf" ) # parse an XML file dom2 = parseString( "Some data some more data" ) print dom1.toxml() print dom2.toxml() }}} == Examples of Use == * node.nodeName * node.nodeValue * node.childNodes === Find Elements === You can manually walk through the {{{childNodes}}} tree, comparing {{{nodeName}}}s. You might be able to use {{{getElementsByTagName}}} as well: {{{ #!python from xml.dom.minidom import parse dom = parse("foo.xml") for node in dom.getElementsByTagName('bar'): # visit every node print node.toxml() }}} {{{getElementsByTagName}}} finds all children of a given name, no matter how deep, thus working recursively. This is usually good, but can cause problems if similar nodes exist at multiple levels and the intervening nodes are important. === Add an Element === Create & add an XML element (Something like {{{}}}) to an XML document. {{{ #!python from xml.dom.minidom import parse dom = parse("bar.xml") x = dom.createElement("foo") # creates dom.childNodes[1].appendChild(x) # appends at end of 1st child's children print dom.toxml() }}} === Add an Element with Text Inside === Create & add an XML element to an XML document, the element has text inside. ex: {{{hello, world!}}} {{{ #!python from xml.dom.minidom import parse dom = parse("bar.xml") x = dom.createElement("foo") # creates txt = dom.createTextNode("hello, world!") # creates "hello, world!" x.appendChild(txt) # results in hello, world! dom.childNodes[1].appendChild(x) # appends at end of 1st child's children print dom.toxml() }}} === Import a Node === You can use DOM 2 "importNode" to take part of one XML document, and put it into another XML document. {{{ #!python from xml.dom.minidom import parse dom1 = parse("foo.xml") dom2 = parse("bar.xml") x = dom1.importNode(dom2.childNodes[1], # take 2nd node in "bar.xml" True) # deep copy dom1.childNodes[1].appendChild(x) # append to children of 2nd node in "foo.xml" print dom1.toxml() }}} == Links == * [[http://docs.python.org/lib/module-xml.dom.minidom.html|Python Library Reference, xml.dom.minidom]] -- API documentation * [[http://www.faqs.org/docs/diveintopython/kgp_divein.html#kgp.divein|Dive into Python, Chapter 5]] -- works almost entirely out of the minidom API == See Also == * [[Sax]], PythonXml