[ACCEPTED]-How do I create an xml document in python-xml

Accepted answer
Score: 13

@Daniel

Thanks for the reply, I also figured 4 out how to do it with the minidom (I'm not 3 sure of the difference between the ElementTree 2 vs the minidom)


from xml.dom.minidom import *
def make_xml():
    doc = Document();
    node = doc.createElement('foo')
    node.appendChild(doc.createTextNode('bar'))
    doc.appendChild(node)
    return doc
if __name__ == '__main__':
    make_xml().writexml(sys.stdout)

I swear I tried this before 1 posting my question...

Score: 9

Setting an attribute on an object won't 5 give a compile-time or a run-time error, it 4 will just do nothing useful if the object 3 doesn't access it (i.e. "node.noSuchAttr = 'bar'" would also not 2 give an error).

Unless you need a specific 1 feature of minidom, I would look at ElementTree:

import sys
from xml.etree.cElementTree import Element, ElementTree

def make_xml():
    node = Element('foo')
    node.text = 'bar'
    doc = ElementTree(node)
    return doc

if __name__ == '__main__':
    make_xml().write(sys.stdout)

More Related questions