Pretty printing XML in Python

后端 未结 26 1740
一个人的身影
一个人的身影 2020-11-22 02:18

What is the best way (or are the various ways) to pretty print XML in Python?

26条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 02:46

    If you're using a DOM implementation, each has their own form of pretty-printing built-in:

    # minidom
    #
    document.toprettyxml()
    
    # 4DOM
    #
    xml.dom.ext.PrettyPrint(document, stream)
    
    # pxdom (or other DOM Level 3 LS-compliant imp)
    #
    serializer.domConfig.setParameter('format-pretty-print', True)
    serializer.writeToString(document)
    

    If you're using something else without its own pretty-printer — or those pretty-printers don't quite do it the way you want —  you'd probably have to write or subclass your own serialiser.

提交回复
热议问题