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

2024-10-03 21:33:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些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。我怎么能把它作为一个文件保存到我的桌面上呢?


Tags: importbuildselfdocdeftagrootxml
2条回答

您可能想在XML DOM树的根节点上使用Node.writexml()。这将把根元素和所有子元素写到一个XML文件中,同时执行所有becessary缩进等操作。

See the documentation for ^{}:

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 files,如果xml是字符串,那么只需将其写入文件即可

xml = "<myxmldata/>"
f =  open("myxmlfile.xml", "wb")
f.write(xml)
f.close()

要从minidom节点获取xml字符串,可以使用

xml = Node.toxml()

也可以直接写入支持写入的对象,例如文件

Node.writexml(f)

相关问题 更多 >