How do I create an xml document in python

后端 未结 2 1820
情歌与酒
情歌与酒 2021-02-07 03:53

Here is my sample code:

from xml.dom.minidom import *
def make_xml():
    doc = Document()
    node = doc.createElement(\'foo\')
    node.innerText = \'bar\'
            


        
2条回答
  •  孤独总比滥情好
    2021-02-07 04:44

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

    Unless you need a specific 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)
    

提交回复
热议问题