0

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

Nasser
  • 2,118
  • 6
  • 33
  • 56

1 Answers1

0

Based on the previous comments, I changed my function as follow and it worked:

def printToFile(self):
        from lxml import etree as ET
        with open('output.xml','a') as file:
            for k,v in self.wordCount.items():
                root = ET.Element(k)
                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)
                file.write(ET.tostring(root, pretty_print=True, xml_declaration=False))
Nasser
  • 2,118
  • 6
  • 33
  • 56