Pretty print in lxml is failing when I add tags to a parsed tree

It has to do with how lxml treats whitespace — see the lxml FAQ for details.

To fix this, change the loading part of the file to the following:

parser = etree.XMLParser(remove_blank_text=True)
root = etree.parse('file.xml', parser).getroot()

I didn’t test it, but it should indent your file just fine with this change.

Leave a Comment