How do I get Python's ElementTree to pretty print to an XML file?

后端 未结 5 1107
猫巷女王i
猫巷女王i 2020-11-28 10:31

Background

I am using SQLite to access a database and retrieve the desired information. I\'m using ElementTree in Python version 2.6 to create an XML file with tha

5条回答
  •  孤独总比滥情好
    2020-11-28 10:58

    If one wants to use lxml, it could be done in the following way:

    from lxml import etree
    
    xml_object = etree.tostring(root,
                                pretty_print=True,
                                xml_declaration=True,
                                encoding='UTF-8')
    
    with open("xmlfile.xml", "wb") as writter:
        writter.write(xml_object)`
    

    If you see xml namespaces e.g. py:pytype="TREE", one might want to add before the creation of xml_object

    etree.cleanup_namespaces(root) 
    

    This should be sufficient for any adaptation in your code.

提交回复
热议问题