我有一些python代码用XML.dom.minidom生成一些XML文本。现在,我从终端运行它,结果它输出一个结构化的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。我怎么能把它作为一个文件保存到我的桌面上呢?
您可能想在XML DOM树的根节点上使用
Node.writexml()
。这将把根元素和所有子元素写到一个XML文件中,同时执行所有becessary缩进等操作。See the documentation for ^{}:
用法有点像:
阅读python files,如果xml是字符串,那么只需将其写入文件即可
要从minidom节点获取xml字符串,可以使用
也可以直接写入支持写入的对象,例如文件
相关问题 更多 >
编程相关推荐