简体   繁体   中英

How to save an XML file to disk with python?

I have some python code to generate some XML text with xml.dom.minidom . Right now, I run it from the terminal and it outputs me a structured XML as a result. I would like it also to generate an XML file and save it to my disk. How could that be done?

This is what I have:

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

This just generates the XML. How could I also have it saved as a file to my desktop?

You probably want to use Node.writexml() on the root node of your XML DOM tree. This will write your root element and all child elements to an XML file, doing all the becessary indenting etc. along the way.

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.

Usage will be somewhat like:

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

Read about python files , if you xml as string you can just write it to a file eg

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

To obtain xml string from minidom nodes you can either use

xml = Node.toxml()

or you can directly write to a object which supports write eg a file

Node.writexml(f)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM