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