Pretty printing XML in Python

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

    I solved this with some lines of code, opening the file, going trough it and adding indentation, then saving it again. I was working with small xml files, and did not want to add dependencies, or more libraries to install for the user. Anyway, here is what I ended up with:

        f = open(file_name,'r')
        xml = f.read()
        f.close()
    
        #Removing old indendations
        raw_xml = ''        
        for line in xml:
            raw_xml += line
    
        xml = raw_xml
    
        new_xml = ''
        indent = '    '
        deepness = 0
    
        for i in range((len(xml))):
    
            new_xml += xml[i]   
            if(i

    It works for me, perhaps someone will have some use of it :)

提交回复
热议问题