Python pretty XML printer with lxml

前端 未结 5 561
一整个雨季
一整个雨季 2020-11-28 09:37

After reading from an existing file with \'ugly\' XML and doing some modifications, pretty printing doesn\'t work. I\'ve tried etree.write(FILE_NAME, pretty_print=True

5条回答
  •  难免孤独
    2020-11-28 10:10

    For me, this issue was not solved until I noticed this little tidbit here:

    http://lxml.de/FAQ.html#why-doesn-t-the-pretty-print-option-reformat-my-xml-output

    Short version:

    Read in the file with this command:

    >>> parser = etree.XMLParser(remove_blank_text=True)
    >>> tree = etree.parse(filename, parser)
    

    That will "reset" the already existing indentation, allowing the output to generate it's own indentation correctly. Then pretty_print as normal:

    >>> tree.write(, pretty_print=True)
    

提交回复
热议问题