xml.dom.minidom —- Minimal DOM implementation

Source code: Lib/xml/dom/minidom.py


xml.dom.minidom is a minimal implementation of the Document Object Model interface, with an API similar to that in other languages. It is intended to be simpler than the full DOM and also significantly smaller. Users who are not already proficient with the DOM should consider using the xml.etree.ElementTree module for their XML processing instead.

警告

The xml.dom.minidom module is not secure against maliciously constructed data. If you need to parse untrusted or unauthenticated data see XML 漏洞.

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

  1. from xml.dom.minidom import parse, parseString
  2. dom1 = parse('c:\\temp\\mydata.xml') # parse an XML file by name
  3. datasource = open('c:\\temp\\mydata.xml')
  4. dom2 = parse(datasource) # parse an open file
  5. dom3 = parseString('<myxml>Some data<empty/> some more data</myxml>')

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

xml.dom.minidom.parse(filename_or_file, parser=None, bufsize=None)

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:

xml.dom.minidom.parseString(string, parser=None)

Return a Document that represents the string. This method creates an io.StringIO object for the string and passes that on to parse().

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

What the parse() and parseString() functions do is connect an XML parser with a “DOM builder” that can accept parse events from any SAX parser and convert them into a DOM tree. The name of the functions are perhaps misleading, but are easy to grasp when learning the interfaces. The parsing of the document will be completed before these functions return; it’s simply that these functions do not provide a parser implementation themselves.

You can also create a Document by calling a method on a “DOM Implementation” object. You can get this object either by calling the getDOMImplementation() function in the xml.dom package or the xml.dom.minidom module. Once you have a Document, you can add child nodes to it to populate the DOM:

  1. from xml.dom.minidom import getDOMImplementation
  2. impl = getDOMImplementation()
  3. newdoc = impl.createDocument(None, "some_tag", None)
  4. top_element = newdoc.documentElement
  5. text = newdoc.createTextNode('Some textual content.')
  6. top_element.appendChild(text)

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:

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

When you are finished with a DOM tree, you may optionally call the unlink() method to encourage early cleanup of the now-unneeded objects. unlink() is an xml.dom.minidom-specific extension to the DOM API that renders the node and its descendants are essentially useless. Otherwise, Python’s garbage collector will eventually take care of the objects in the tree.

参见

Document Object Model (DOM) Level 1 Specification

The W3C recommendation for the DOM supported by xml.dom.minidom.

DOM Objects

The definition of the DOM API for Python is given as part of the xml.dom module documentation. This section lists the differences between the API and xml.dom.minidom.

Node.unlink()

Break internal references within the DOM so that it will be garbage collected on versions of Python without cyclic GC. Even when cyclic GC is available, using this can make large amounts of memory available sooner, so calling this on DOM objects as soon as they are no longer needed is good practice. This only needs to be called on the Document object, but may be called on child nodes to discard children of that node.

You can avoid calling this method explicitly by using the with statement. The following code will automatically unlink dom when the with block is exited:

  1. with xml.dom.minidom.parse(datasource) as dom:
  2. ... # Work with dom.

Node.writexml(writer, indent="", addindent="", newl="",

encoding=None, standalone=None)

Write XML to the writer object. The writer receives texts but not bytes as input, it should have a write() method which matches that of the file object interface. The indent parameter is the indentation of the current node. The addindent parameter is the incremental indentation to use for subnodes of the current one. The newl parameter specifies the string to use to terminate newlines.

For the Document node, an additional keyword argument encoding can be used to specify the encoding field of the XML header.

Silimarly, explicitly stating the standalone argument causes the standalone document declarations to be added to the prologue of the XML document. If the value is set to True, standalone=”yes” is added, otherwise it is set to “no”. Not stating the argument will omit the declaration from the document.

在 3.8 版更改: The writexml() method now preserves the attribute order specified by the user.

Node.toxml(encoding=None, standalone=None)

Return a string or byte string containing the XML represented by the DOM node.

With an explicit encoding 1 argument, the result is a byte string in the specified encoding. With no encoding argument, the result is a Unicode string, and the XML declaration in the resulting string does not specify an encoding. Encoding this string in an encoding other than UTF-8 is likely incorrect, since UTF-8 is the default encoding of XML.

The standalone argument behaves exactly as in writexml().

在 3.8 版更改: The toxml() method now preserves the attribute order specified by the user.

Node.toprettyxml(indent="\t", newl="\n", encoding=None,

standalone=None)

Return a pretty-printed version of the document. indent specifies the indentation string and defaults to a tabulator; newl specifies the string emitted at the end of each line and defaults to \n.

The encoding argument behaves like the corresponding argument of toxml().

The standalone argument behaves exactly as in writexml().

在 3.8 版更改: The toprettyxml() method now preserves the attribute order specified by the user.

DOM Example

This example program is a fairly realistic example of a simple program. In this particular case, we do not take much advantage of the flexibility of the DOM.

  1. import xml.dom.minidom
  2. document = """\
  3. <slideshow>
  4. <title>Demo slideshow</title>
  5. <slide><title>Slide title</title>
  6. <point>This is a demo</point>
  7. <point>Of a program for processing slides</point>
  8. </slide>
  9. <slide><title>Another demo slide</title>
  10. <point>It is important</point>
  11. <point>To have more than</point>
  12. <point>one slide</point>
  13. </slide>
  14. </slideshow>
  15. """
  16. dom = xml.dom.minidom.parseString(document)
  17. def getText(nodelist):
  18. rc = []
  19. for node in nodelist:
  20. if node.nodeType == node.TEXT_NODE:
  21. rc.append(node.data)
  22. return ''.join(rc)
  23. def handleSlideshow(slideshow):
  24. print("<html>")
  25. handleSlideshowTitle(slideshow.getElementsByTagName("title")[0])
  26. slides = slideshow.getElementsByTagName("slide")
  27. handleToc(slides)
  28. handleSlides(slides)
  29. print("</html>")
  30. def handleSlides(slides):
  31. for slide in slides:
  32. handleSlide(slide)
  33. def handleSlide(slide):
  34. handleSlideTitle(slide.getElementsByTagName("title")[0])
  35. handlePoints(slide.getElementsByTagName("point"))
  36. def handleSlideshowTitle(title):
  37. print("<title>%s</title>" % getText(title.childNodes))
  38. def handleSlideTitle(title):
  39. print("<h2>%s</h2>" % getText(title.childNodes))
  40. def handlePoints(points):
  41. print("<ul>")
  42. for point in points:
  43. handlePoint(point)
  44. print("</ul>")
  45. def handlePoint(point):
  46. print("<li>%s</li>" % getText(point.childNodes))
  47. def handleToc(slides):
  48. for slide in slides:
  49. title = slide.getElementsByTagName("title")[0]
  50. print("<p>%s</p>" % getText(title.childNodes))
  51. handleSlideshow(dom)

minidom and the DOM standard

The xml.dom.minidom module is essentially a DOM 1.0-compatible DOM with some DOM 2 features (primarily namespace features).

Usage of the DOM interface in Python is straight-forward. The following mapping rules apply:

  • Interfaces are accessed through instance objects. Applications should not instantiate the classes themselves; they should use the creator functions available on the Document object. Derived interfaces support all operations (and attributes) from the base interfaces, plus any new operations.

  • Operations are used as methods. Since the DOM uses only in parameters, the arguments are passed in normal order (from left to right). There are no optional arguments. void operations return None.

  • IDL attributes map to instance attributes. For compatibility with the OMG IDL language mapping for Python, an attribute foo can also be accessed through accessor methods _get_foo() and _set_foo(). readonly attributes must not be changed; this is not enforced at runtime.

  • The types short int, unsigned int, unsigned long long, and boolean all map to Python integer objects.

  • The type DOMString maps to Python strings. xml.dom.minidom supports either bytes or strings, but will normally produce strings. Values of type DOMString may also be None where allowed to have the IDL null value by the DOM specification from the W3C.

  • const declarations map to variables in their respective scope (e.g. xml.dom.minidom.Node.PROCESSING_INSTRUCTION_NODE); they must not be changed.

  • DOMException is currently not supported in xml.dom.minidom. Instead, xml.dom.minidom uses standard Python exceptions such as TypeError and AttributeError.

  • NodeList objects are implemented using Python’s built-in list type. These objects provide the interface defined in the DOM specification, but with earlier versions of Python they do not support the official API. They are, however, much more “Pythonic” than the interface defined in the W3C recommendations.

The following interfaces have no implementation in xml.dom.minidom:

  • DOMTimeStamp

  • EntityReference

Most of these reflect information in the XML document that is not of general utility to most DOM users.

脚注

1

The encoding name included in the XML output should conform to the appropriate standards. For example, “UTF-8” is valid, but “UTF8” is not valid in an XML document’s declaration, even though Python accepts it as an encoding name. See https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl and https://www.iana.org/assignments/character-sets/character-sets.xhtml.