Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save an XML file to disk with python?

Tags:

python

file

xml

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?

like image 206
Lucas Pereira Avatar asked Mar 28 '12 17:03

Lucas Pereira


People also ask

Can you use XML with Python?

Python enables you to parse and modify XML documents. In order to parse XML document, you need to have the entire XML document in memory.


1 Answers

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

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 e.g. a file

Node.writexml(f)
like image 200
Anurag Uniyal Avatar answered Nov 16 '22 00:11

Anurag Uniyal