What is the best way (or are the various ways) to pretty print XML in Python?
Use etree.indent and etree.tostring
import lxml.etree as etree
root = etree.fromstring('Welcome
')
etree.indent(root, space=" ")
xml_string = etree.tostring(root, pretty_print=True).decode()
print(xml_string)
output
Welcome
Removing namespaces and prefixes
import lxml.etree as etree
def dump_xml(element):
for item in element.getiterator():
item.tag = etree.QName(item).localname
etree.cleanup_namespaces(element)
etree.indent(element, space=" ")
result = etree.tostring(element, pretty_print=True).decode()
return result
root = etree.fromstring('hello world ')
xml_string = dump_xml(root)
print(xml_string)
output
hello world