How to save XML file to disk using python?

I have python code to generate XML text using xml.dom.minidom. Right now, I am running it from the terminal, and as a result, it displays me structured XML. I would also like to create an XML file and save it to my disk. How can I do that?

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

It just generates XML. How could I also save it as a file on the desktop?

+5
source share
2 answers

You probably want to use the Node.writexml()XML DOM in the node root of your tree. This will write your root element and all child elements to an XML file, doing all the necessary indentation, etc. On this way.

See the documentation for xml.dom.minidom:

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

XML . write(), . indent - node. addindent - . newl , .

node XML.

2.1: , addindent newl .

2.3: node XML .

:

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

python xml , , .

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

xml -,

xml = Node.toxml()

, , .

Node.writexml(f)
+6

All Articles