Python打印到文件为XML

时间:2015-11-16 15:21:18

标签: python xml

在以下函数中,我想将嵌入字典的项目显示为XML树并将其打印到文件中。

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)

当我运行代码时,所有项目都显示在控制台屏幕中,但问题是它只打印文件中的最后一项。

在控制台中,我得到了这个:

<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>

但是当我打开文件时,我只得到了这个:

<nice>
  <DocID>3</DocID>
  <Occurences>1</Occurences>
</nice>

有人可以帮我解决这个问题。感谢

1 个答案:

答案 0 :(得分:0)

根据之前的评论,我改变了我的功能,如下所示:

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))