Changing the default indentation of etree.tostring in lxml

Since version 4.5, you can set indent size using indent() function.

etree.indent(root, space="    ")
print(etree.tostring(root))

As said in this thread, there is no real way to change the indent of the lxml.etree.tostring pretty-print.

But, you can:

  • add a XSLT transform to change the indent
  • add whitespace to the tree, with something like in the cElementTree library

code:

def indent(elem, level=0):
    i = "\n" + level*"  "
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + "  "
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
        for elem in elem:
            indent(elem, level+1)
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
    else:
        if level and (not elem.tail or not elem.tail.strip()):
            elem.tail = i