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?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With