Pretty printing XML in Python

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

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

26条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 03:09

    Here's my (hacky?) solution to get around the ugly text node problem.

    uglyXml = doc.toprettyxml(indent='  ')
    
    text_re = re.compile('>\n\s+([^<>\s].*?)\n\s+\g<1>

    The above code will produce:

    
    
      
        1
        Add Visual Studio 2005 and 2008 solution files
        
    We need Visual Studio 2005/2008 project files for Windows.

    Instead of this:

    
    
      
        
          1
        
        
          Add Visual Studio 2005 and 2008 solution files
        
        
    We need Visual Studio 2005/2008 project files for Windows.

    Disclaimer: There are probably some limitations.

提交回复
热议问题