13.6 xml.dom.minidom -- Lightweight DOM implementation

New in version 2.0.

xml.dom.minidom is a light-weight implementation of the Document Object Model interface. It is intended to be simpler than the full DOM and also significantly smaller.

DOM applications typically start by parsing some XML into a DOM. With xml.dom.minidom, this is done through the parse functions:

from xml.dom.minidom import parse, parseString

dom1 = parse('c:\\temp\\mydata.xml') # parse an XML file by name

datasource = open('c:\\temp\\mydata.xml')
dom2 = parse(datasource)   # parse an open file

dom3 = parseString('<myxml>Some data<empty/> some more data</myxml>')

The parse function can take either a filename or an open file object.

parse(filename_or_file, parser)
Return a Document from the given input. filename_or_file may be either a file name, or a file-like object. parser, if given, must be a SAX2 parser object. This function will change the document handler of the parser and activate namespace support; other parser configuration (like setting an entity resolver) must have been done in advance.

If you have XML in a string, you can use the parseString() function instead:

parseString(string[, parser])
Return a Document that represents the string. This method creates a StringIO object for the string and passes that on to parse.

Both functions return a Document object representing the content of the document.

You can also create a Document node merely by instantiating a document object. Then you could add child nodes to it to populate the DOM:

from xml.dom.minidom import Document

newdoc = Document()
newel = newdoc.createElement("some_tag")
newdoc.appendChild(newel)

Once you have a DOM document object, you can access the parts of your XML document through its properties and methods. These properties are defined in the DOM specification. The main property of the document object is the documentElement property. It gives you the main element in the XML document: the one that holds all others. Here is an example program:

dom3 = parseString("<myxml>Some data</myxml>")
assert dom3.documentElement.tagName == "myxml"

When you are finished with a DOM, you should clean it up. This is necessary because some versions of Python do not support garbage collection of objects that refer to each other in a cycle. Until this restriction is removed from all versions of Python, it is safest to write your code as if cycles would not be cleaned up.

The way to clean up a DOM is to call its unlink() method:

dom1.unlink()
dom2.unlink()
dom3.unlink()

unlink() is a xml.dom.minidom-specific extension to the DOM API. After calling unlink() on a node, the node and its descendents are essentially useless.

See Also:

Document Object Model (DOM) Level 1 Specification
The W3C recommendation for the DOM supported by xml.dom.minidom.


Subsections
See About this document... for information on suggesting changes.