In the following function, I want to display the items of an embedded dictionary as XML tree and print it to a file.
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)
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.
In the console, I got this:
<weather>
<DocID>1</DocID>
<Occurences>1</Occurences>
</weather>
<london>
<DocID>1</DocID>
<Occurences>1</Occurences>
<DocID>2</DocID>
<Occurences>2</Occurences>
<DocID>3</DocID>
<Occurences>1</Occurences>
</london>
<expens>
<DocID>2</DocID>
<Occurences>1</Occurences>
</expens>
<nice>
<DocID>3</DocID>
<Occurences>1</Occurences>
</nice>
but when I open the file, I only got this:
<nice>
<DocID>3</DocID>
<Occurences>1</Occurences>
</nice>
Can someone help me solving this issue. Thanks