gpt4 book ai didi

python - 如何使用 python 将 XML 文件保存到磁盘?

转载 作者:太空狗 更新时间:2023-10-29 20:39:02 24 4
gpt4 key购买 nike

我有一些 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 文件,同时执行所有必要的缩进等操作。

See the documentation for xml.dom.minidom:

Node.writexml(writer[, indent=""[, addindent=""[, newl=""]]])

Write XML to the writer object. The writer should have a write() method which matches that of the file object interface. The indent parameter is the indentation of the current node. The addindent parameter is the incremental indentation to use for subnodes of the current one. The newl parameter specifies the string to use to terminate newlines.

For the Document node, an additional keyword argument encoding can be used to specify the encoding field of the XML header.

Changed in version 2.1: The optional keyword parameters indent, addindent, and newl were added to support pretty output.

Changed in version 2.3: For the Document node, an additional keyword argument encoding can be used to specify the encoding field of the XML header.

用法有点像:

file_handle = open("filename.xml","wb")
Your_Root_Node.writexml(file_handle)
file_handle.close()

关于python - 如何使用 python 将 XML 文件保存到磁盘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9912578/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com