Posted By

Twain on 12/29/09


Tagged

xml elementtree indent


Versions (?)

Indent XML using ElementTree


 / Published in: Python
 

URL: http://effbot.org/zone/element-lib.htm

This is a custom function in the elementree documenation, copied here for reference.

  1. def indent(elem, level=0):
  2. i = "\n" + level*" "
  3. if len(elem):
  4. if not elem.text or not elem.text.strip():
  5. elem.text = i + " "
  6. if not elem.tail or not elem.tail.strip():
  7. elem.tail = i
  8. for elem in elem:
  9. indent(elem, level+1)
  10. if not elem.tail or not elem.tail.strip():
  11. elem.tail = i
  12. else:
  13. if level and (not elem.tail or not elem.tail.strip()):
  14. elem.tail = i
  15.  
  16. def printxml(xml):
  17. import xml.etree.ElementTree as et
  18. elem = et.fromstring(xml)
  19. indent(elem)
  20. print et.tostring(elem)

Report this snippet  

You need to login to post a comment.