Changing and Generating XML
Just like for HTML and other kinds of structured text, the simplest way to output an XML document is often to prepare and write it using Python’s normal string and file operations, covered in Chapter 9 and File Objects. Templating (covered in Templating) is also often the best approach. Subclassing class XMLGenerator (covered in “XMLGenerator” in The xml.sax.saxutils module) is a good way to generate an XML document that is like an input XML document except for a few changes.
The xml.dom.minidom module offers yet another possibility because its classes support methods to generate, insert, remove, and alter nodes in a DOM tree that represents the document. You can create a DOM tree by parsing and then alter it, or you can create an empty DOM tree and populate it from scratch. You can output the resulting XML document with methods toxml, toprettyxml, or writexml of the Document instance. You can also output a subtree by calling these methods on the Node that is the subtree’s root. The ElementTree module, mentioned in this chapter’s introduction, also offers similar functionality (but with a more Pythonic API and much better performance).
Factory Methods of a Document Object
The Document class supplies factory methods to create instances of Node subclasses. The most frequently used factory methods of a Document instance d are as follows.
createComment |
Builds and returns an instance |
createElement ... |
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access