6.2 Printing The Tree

We'll use a single example document throughout this section. Here's the sample:

<?xml version="1.0" encoding="iso-8859-1"?>
<xbel>  
  <?processing instruction?>
  <desc>No description</desc>
  <folder>
    <title>XML bookmarks</title>
    <bookmark href="http://www.python.org/sigs/xml-sig/" >
      <title>SIG for XML Processing in Python</title>
    </bookmark>
  </folder>
</xbel>

Converted to a DOM tree, this document could produce the following tree.

Element xbel None
   Text #text '  \012  '
   ProcessingInstruction processing 'instruction'
   Text #text '\012  '
   Element desc None
      Text #text 'No description'
   Text #text '\012  '
   Element folder None
      Text #text '\012    '
      Element title None
         Text #text 'XML bookmarks'
      Text #text '\012    '
      Element bookmark None
         Text #text '\012      '
         Element title None
            Text #text 'SIG for XML Processing in Python'
         Text #text '\012    '
      Text #text '\012  '
   Text #text '\012'

This isn't the only possible tree, because different parsers may differ in how they generate Text nodes; any of the Text nodes in the above tree might be split into multiple nodes.

A DOM tree can be converted back to XML by using the Print(doc, stream) or PrettyPrint(doc, stream) functions in the xml.dom.ext module. If stream isn't provided, the resulting XML will be printed to standard output. Print() will simply render the DOM tree without any changes, while PrettyPrint() will add or remove whitespace in order to nicely indent the resulting XML.