title: Python print to file as XML
body: <p>In the following function, I want to display the items of an embedded dictionary as XML tree and print it to a file.</p>
  
  <pre><code>def printToFile(self):
          from lxml import etree as ET
          for k,v in self.wordCount.items():
              root = ET.Element(k)
              tree = ET.ElementTree(root)
              for k1,v1 in v.items():
                  DocID = ET.SubElement(root, 'DocID')
                  DocID.text = str(k1)
                  Occurences = ET.SubElement(root, 'Occurences')
                  Occurences.text = str(v1)
              print ET.tostring(root, pretty_print=True, xml_declaration=False)
              tree.write('output.xml', pretty_print=True, xml_declaration=False)
  </code></pre>
  
  <p>When I run the code, all the items are shown in the console screen but the problem is that it only prints the last item in the file.</p>
  
  <p>In the console, I got this:</p>
  
  <pre><code>&lt;weather&gt;
    &lt;DocID&gt;1&lt;/DocID&gt;
    &lt;Occurences&gt;1&lt;/Occurences&gt;
  &lt;/weather&gt;
  
  &lt;london&gt;
    &lt;DocID&gt;1&lt;/DocID&gt;
    &lt;Occurences&gt;1&lt;/Occurences&gt;
    &lt;DocID&gt;2&lt;/DocID&gt;
    &lt;Occurences&gt;2&lt;/Occurences&gt;
    &lt;DocID&gt;3&lt;/DocID&gt;
    &lt;Occurences&gt;1&lt;/Occurences&gt;
  &lt;/london&gt;
  
  &lt;expens&gt;
    &lt;DocID&gt;2&lt;/DocID&gt;
    &lt;Occurences&gt;1&lt;/Occurences&gt;
  &lt;/expens&gt;
  
  &lt;nice&gt;
    &lt;DocID&gt;3&lt;/DocID&gt;
    &lt;Occurences&gt;1&lt;/Occurences&gt;
  &lt;/nice&gt;
  </code></pre>
  
  <p>but when I open the file, I only got this:</p>
  
  <pre><code>&lt;nice&gt;
    &lt;DocID&gt;3&lt;/DocID&gt;
    &lt;Occurences&gt;1&lt;/Occurences&gt;
  &lt;/nice&gt;
  </code></pre>
  
  <p>Can someone help me solving this issue. Thanks</p>