Pretty printing XML in Python

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

    If you have xmllint you can spawn a subprocess and use it. xmllint --format pretty-prints its input XML to standard output.

    Note that this method uses an program external to python, which makes it sort of a hack.

    def pretty_print_xml(xml):
        proc = subprocess.Popen(
            ['xmllint', '--format', '/dev/stdin'],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
        )
        (output, error_output) = proc.communicate(xml);
        return output
    
    print(pretty_print_xml(data))
    

提交回复
热议问题