2014年7月17日星期四

One function that makes writting xml file pretty

One function that makes writting xml file pretty

By default, if you use ElementTree to write a new xml file, you will find the new xml file is a single line file, which is not pretty to read by human. Below function will do the trick to make it multiple line and more pretty
        def indent(self,elem, level=0):
            """
            One function that makes writting xml file pretty
            """
            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:
                    self.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

Using it is very simple, just get the element root and then indent it.
            root = xml_tree.getroot()
            indent(root, level=0)
            xml_tree.write("file")
Fordward from http://effbot.org/zone/element-lib.htm#prettyprint and http://www.gossamer-threads.com/lists/python/python/831813