Pretty printing XML in Python

后端 未结 26 1738
一个人的身影
一个人的身影 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 for some reason you can't get your hands on any of the Python modules that other users mentioned, I suggest the following solution for Python 2.7:

    import subprocess
    
    def makePretty(filepath):
      cmd = "xmllint --format " + filepath
      prettyXML = subprocess.check_output(cmd, shell = True)
      with open(filepath, "w") as outfile:
        outfile.write(prettyXML)
    

    As far as I know, this solution will work on Unix-based systems that have the xmllint package installed.

提交回复
热议问题