如何使用Python将XML文件保存到磁盘上?
如何使用Python将XML文件保存到磁盘上?
我有一些使用xml.dom.minidom生成XML文本的Python代码。目前,我通过终端运行它,并将结构化的XML作为结果输出。我希望它也能生成一个XML文件并保存到我的硬盘上。该如何实现呢?
这是我的代码:
import xml from xml.dom.minidom import Document import copy class dict2xml(object): doc = Document() def __init__(self, structure): if len(structure) == 1: rootName = str(structure.keys()[0]) self.root = self.doc.createElement(rootName) self.doc.appendChild(self.root) self.build(self.root, structure[rootName]) def build(self, father, structure): if type(structure) == dict: for k in structure: tag = self.doc.createElement(k) father.appendChild(tag) self.build(tag, structure[k]) elif type(structure) == list: grandFather = father.parentNode tagName = father.tagName # grandFather.removeChild(father) for l in structure: tag = self.doc.createElement(tagName.rstrip('s')) self.build(tag, l) father.appendChild(tag) else: data = str(structure) tag = self.doc.createTextNode(data) father.appendChild(tag) def display(self): print self.doc.toprettyxml(indent=" ")
这只是生成XML的代码。我该如何将它保存为一个文件到我的桌面上呢?