Pretty printing XML in Python

后端 未结 26 1803
一个人的身影
一个人的身影 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 03:10

    I found this question while looking for "how to pretty print html"

    Using some of the ideas in this thread I adapted the XML solutions to work for XML or HTML:

    from xml.dom.minidom import parseString as string_to_dom
    
    def prettify(string, html=True):
        dom = string_to_dom(string)
        ugly = dom.toprettyxml(indent="  ")
        split = list(filter(lambda x: len(x.strip()), ugly.split('\n')))
        if html:
            split = split[1:]
        pretty = '\n'.join(split)
        return pretty
    
    def pretty_print(html):
        print(prettify(html))
    

    When used this is what it looks like:

    html = """\
    

    'IDK!'


    Hi

    Try for 2

    Oh No!
    """ pretty_print(html)

    Which returns:

    'IDK!'


    Hi

    Try for 2

    Oh No!

提交回复
热议问题