blob: 1af07b3a377d6490865446cba51b0f0ec5554c85 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`xml.dom.minidom` --- Lightweight DOM implementation
3=========================================================
4
5.. module:: xml.dom.minidom
6 :synopsis: Lightweight Document Object Model (DOM) implementation.
7.. moduleauthor:: Paul Prescod <paul@prescod.net>
8.. sectionauthor:: Paul Prescod <paul@prescod.net>
9.. sectionauthor:: Martin v. Löwis <martin@v.loewis.de>
10
11
Georg Brandl116aa622007-08-15 14:28:22 +000012:mod:`xml.dom.minidom` is a light-weight implementation of the Document Object
13Model interface. It is intended to be simpler than the full DOM and also
14significantly smaller.
15
16DOM applications typically start by parsing some XML into a DOM. With
17:mod:`xml.dom.minidom`, this is done through the parse functions::
18
19 from xml.dom.minidom import parse, parseString
20
21 dom1 = parse('c:\\temp\\mydata.xml') # parse an XML file by name
22
23 datasource = open('c:\\temp\\mydata.xml')
24 dom2 = parse(datasource) # parse an open file
25
26 dom3 = parseString('<myxml>Some data<empty/> some more data</myxml>')
27
28The :func:`parse` function can take either a filename or an open file object.
29
30
31.. function:: parse(filename_or_file, parser)
32
33 Return a :class:`Document` from the given input. *filename_or_file* may be
34 either a file name, or a file-like object. *parser*, if given, must be a SAX2
35 parser object. This function will change the document handler of the parser and
36 activate namespace support; other parser configuration (like setting an entity
37 resolver) must have been done in advance.
38
39If you have XML in a string, you can use the :func:`parseString` function
40instead:
41
42
43.. function:: parseString(string[, parser])
44
45 Return a :class:`Document` that represents the *string*. This method creates a
46 :class:`StringIO` object for the string and passes that on to :func:`parse`.
47
48Both functions return a :class:`Document` object representing the content of the
49document.
50
51What the :func:`parse` and :func:`parseString` functions do is connect an XML
52parser with a "DOM builder" that can accept parse events from any SAX parser and
53convert them into a DOM tree. The name of the functions are perhaps misleading,
54but are easy to grasp when learning the interfaces. The parsing of the document
55will be completed before these functions return; it's simply that these
56functions do not provide a parser implementation themselves.
57
58You can also create a :class:`Document` by calling a method on a "DOM
59Implementation" object. You can get this object either by calling the
60:func:`getDOMImplementation` function in the :mod:`xml.dom` package or the
61:mod:`xml.dom.minidom` module. Using the implementation from the
62:mod:`xml.dom.minidom` module will always return a :class:`Document` instance
63from the minidom implementation, while the version from :mod:`xml.dom` may
64provide an alternate implementation (this is likely if you have the `PyXML
65package <http://pyxml.sourceforge.net/>`_ installed). Once you have a
66:class:`Document`, you can add child nodes to it to populate the DOM::
67
68 from xml.dom.minidom import getDOMImplementation
69
70 impl = getDOMImplementation()
71
72 newdoc = impl.createDocument(None, "some_tag", None)
73 top_element = newdoc.documentElement
74 text = newdoc.createTextNode('Some textual content.')
75 top_element.appendChild(text)
76
77Once you have a DOM document object, you can access the parts of your XML
78document through its properties and methods. These properties are defined in
79the DOM specification. The main property of the document object is the
80:attr:`documentElement` property. It gives you the main element in the XML
81document: the one that holds all others. Here is an example program::
82
83 dom3 = parseString("<myxml>Some data</myxml>")
84 assert dom3.documentElement.tagName == "myxml"
85
86When you are finished with a DOM, you should clean it up. This is necessary
87because some versions of Python do not support garbage collection of objects
88that refer to each other in a cycle. Until this restriction is removed from all
89versions of Python, it is safest to write your code as if cycles would not be
90cleaned up.
91
92The way to clean up a DOM is to call its :meth:`unlink` method::
93
94 dom1.unlink()
95 dom2.unlink()
96 dom3.unlink()
97
98:meth:`unlink` is a :mod:`xml.dom.minidom`\ -specific extension to the DOM API.
99After calling :meth:`unlink` on a node, the node and its descendants are
100essentially useless.
101
102
103.. seealso::
104
105 `Document Object Model (DOM) Level 1 Specification <http://www.w3.org/TR/REC-DOM-Level-1/>`_
106 The W3C recommendation for the DOM supported by :mod:`xml.dom.minidom`.
107
108
109.. _minidom-objects:
110
111DOM Objects
112-----------
113
114The definition of the DOM API for Python is given as part of the :mod:`xml.dom`
115module documentation. This section lists the differences between the API and
116:mod:`xml.dom.minidom`.
117
118
119.. method:: Node.unlink()
120
121 Break internal references within the DOM so that it will be garbage collected on
122 versions of Python without cyclic GC. Even when cyclic GC is available, using
123 this can make large amounts of memory available sooner, so calling this on DOM
124 objects as soon as they are no longer needed is good practice. This only needs
125 to be called on the :class:`Document` object, but may be called on child nodes
126 to discard children of that node.
127
128
129.. method:: Node.writexml(writer[,indent=""[,addindent=""[,newl=""]]])
130
131 Write XML to the writer object. The writer should have a :meth:`write` method
132 which matches that of the file object interface. The *indent* parameter is the
133 indentation of the current node. The *addindent* parameter is the incremental
134 indentation to use for subnodes of the current one. The *newl* parameter
135 specifies the string to use to terminate newlines.
136
Georg Brandl55ac8f02007-09-01 13:51:09 +0000137 For the :class:`Document` node, an additional keyword argument *encoding* can be
138 used to specify the encoding field of the XML header.
Georg Brandl116aa622007-08-15 14:28:22 +0000139
140
141.. method:: Node.toxml([encoding])
142
143 Return the XML that the DOM represents as a string.
144
145 With no argument, the XML header does not specify an encoding, and the result is
146 Unicode string if the default encoding cannot represent all characters in the
147 document. Encoding this string in an encoding other than UTF-8 is likely
148 incorrect, since UTF-8 is the default encoding of XML.
149
150 With an explicit *encoding* argument, the result is a byte string in the
151 specified encoding. It is recommended that this argument is always specified. To
152 avoid :exc:`UnicodeError` exceptions in case of unrepresentable text data, the
153 encoding argument should be specified as "utf-8".
154
Georg Brandl116aa622007-08-15 14:28:22 +0000155
Georg Brandl55ac8f02007-09-01 13:51:09 +0000156.. method:: Node.toprettyxml([indent[, newl[, encoding]]])
Georg Brandl116aa622007-08-15 14:28:22 +0000157
158 Return a pretty-printed version of the document. *indent* specifies the
159 indentation string and defaults to a tabulator; *newl* specifies the string
160 emitted at the end of each line and defaults to ``\n``.
161
Georg Brandl55ac8f02007-09-01 13:51:09 +0000162 There's also an *encoding* argument; see :meth:`toxml`.
Georg Brandl116aa622007-08-15 14:28:22 +0000163
Georg Brandl116aa622007-08-15 14:28:22 +0000164
165The following standard DOM methods have special considerations with
166:mod:`xml.dom.minidom`:
167
Georg Brandl116aa622007-08-15 14:28:22 +0000168.. method:: Node.cloneNode(deep)
169
170 Although this method was present in the version of :mod:`xml.dom.minidom`
171 packaged with Python 2.0, it was seriously broken. This has been corrected for
172 subsequent releases.
173
174
175.. _dom-example:
176
177DOM Example
178-----------
179
180This example program is a fairly realistic example of a simple program. In this
181particular case, we do not take much advantage of the flexibility of the DOM.
182
183.. literalinclude:: ../includes/minidom-example.py
184
185
186.. _minidom-and-dom:
187
188minidom and the DOM standard
189----------------------------
190
191The :mod:`xml.dom.minidom` module is essentially a DOM 1.0-compatible DOM with
192some DOM 2 features (primarily namespace features).
193
194Usage of the DOM interface in Python is straight-forward. The following mapping
195rules apply:
196
197* Interfaces are accessed through instance objects. Applications should not
198 instantiate the classes themselves; they should use the creator functions
199 available on the :class:`Document` object. Derived interfaces support all
200 operations (and attributes) from the base interfaces, plus any new operations.
201
202* Operations are used as methods. Since the DOM uses only :keyword:`in`
203 parameters, the arguments are passed in normal order (from left to right).
204 There are no optional arguments. :keyword:`void` operations return ``None``.
205
206* IDL attributes map to instance attributes. For compatibility with the OMG IDL
207 language mapping for Python, an attribute ``foo`` can also be accessed through
208 accessor methods :meth:`_get_foo` and :meth:`_set_foo`. :keyword:`readonly`
209 attributes must not be changed; this is not enforced at runtime.
210
211* The types ``short int``, ``unsigned int``, ``unsigned long long``, and
212 ``boolean`` all map to Python integer objects.
213
214* The type ``DOMString`` maps to Python strings. :mod:`xml.dom.minidom` supports
215 either byte or Unicode strings, but will normally produce Unicode strings.
216 Values of type ``DOMString`` may also be ``None`` where allowed to have the IDL
217 ``null`` value by the DOM specification from the W3C.
218
219* :keyword:`const` declarations map to variables in their respective scope (e.g.
220 ``xml.dom.minidom.Node.PROCESSING_INSTRUCTION_NODE``); they must not be changed.
221
222* ``DOMException`` is currently not supported in :mod:`xml.dom.minidom`.
223 Instead, :mod:`xml.dom.minidom` uses standard Python exceptions such as
224 :exc:`TypeError` and :exc:`AttributeError`.
225
226* :class:`NodeList` objects are implemented using Python's built-in list type.
227 Starting with Python 2.2, these objects provide the interface defined in the DOM
228 specification, but with earlier versions of Python they do not support the
229 official API. They are, however, much more "Pythonic" than the interface
230 defined in the W3C recommendations.
231
232The following interfaces have no implementation in :mod:`xml.dom.minidom`:
233
234* :class:`DOMTimeStamp`
235
236* :class:`DocumentType` (added in Python 2.1)
237
238* :class:`DOMImplementation` (added in Python 2.1)
239
240* :class:`CharacterData`
241
242* :class:`CDATASection`
243
244* :class:`Notation`
245
246* :class:`Entity`
247
248* :class:`EntityReference`
249
250* :class:`DocumentFragment`
251
252Most of these reflect information in the XML document that is not of general
253utility to most DOM users.
254