I have an XML document which I'm pretty-printing using lxml.etree.tostring
print etree.tostring(doc, pretty_print=True)
The default level of indentation is 2 spaces, and I'd like to change this to 4 spaces. There isn't any argument for this in the tostring
function; is there a way to do this easily with lxml?
The lxml XML toolkit is a Pythonic binding for the C libraries libxml2 and libxslt. It is unique in that it combines the speed and XML feature completeness of these libraries with the simplicity of a native Python API, mostly compatible but superior to the well-known ElementTree API.
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With