Hi guys,

a not so complex question:

form xml.etree.ElementTree import *
>>> tostring("<home><room>bedroom</room></home>")

I would like to have the indentation in for the string. Something like:


Of course my document is a little complex. Is it possible to have it in an automatic way? And if not, could you suggest me an easy way to do it?

Thank you.

Check my pretty lib for list and tuple for inspiration (see code snippets).

I know a method which uses the (great) lxml module instead of ElementTree. The lxml.etree.tostring() method accepts a 'pretty_print' keyword argument. See the example here http://codespeak.net/lxml/tutorial.html#serialisation .
In your case

>>> from lxml import etree
>>> root = etree.XML("<home><room>bedroom</room></home>")
>>> print(etree.tostring(root, pretty_print=True))

Thanks for the answers. lxml works nice :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.