inserting newlines in xml file generated via xml.etree.ElementTree in python

前端 未结 5 1634
北海茫月
北海茫月 2020-12-02 17:12

I have created a xml file using xml.etree.ElementTree in python. I then use

tree.write(filename, "UTF-8") 

to write out the documen

5条回答
  •  情书的邮戳
    2020-12-02 17:23

    There is no pretty printing support in ElementTree, but you can utilize other XML modules.

    For example, xml.dom.minidom.Node.toprettyxml():

    Node.toprettyxml([indent=""[, newl=""[, encoding=""]]])

    Return a pretty-printed version of the document. indent specifies the indentation string and defaults to a tabulator; newl specifies the string emitted at the end of each line and defaults to \n.

    Use indent and newl to fit your requirements.

    An example, using the default formatting characters:

    >>> from xml.dom import minidom
    >>> from xml.etree import ElementTree
    >>> tree1=ElementTree.XML('12')
    >>> ElementTree.tostring(tree1)
    '12'
    >>> print minidom.parseString(ElementTree.tostring(tree1)).toprettyxml()
    
    
        
            1
        
        
            2
        
    
    
    >>> 
    

提交回复
热议问题