/Doc/library/xml.dom.minidom.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 273 lines · 182 code · 91 blank · 0 comment · 0 complexity · d97820d38e7a30790add2ad290958efe MD5 · raw file

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