Search code examples
pythonxmlformatelementtreeprettify

Python - write Xml (formatted)


I wrote this python script in order to create Xml content and i would like to write this "prettified" xml to a file (50% done):

My script so far:

    data = ET.Element("data")

    project = ET.SubElement(data, "project")        
    project.text = "This project text"

    rawString = ET.tostring(data, "utf-8")
    reparsed = xml.dom.minidom.parseString(rawString)

    cleanXml = reparsed.toprettyxml(indent="    ")

    # This prints the prettified xml i would like to save to a file
    print cleanXml

    # This part does not work, the only parameter i can pass is "data"
    # But when i pass "data" as a parameter, a xml-string is written to the file
    tree = ET.ElementTree(cleanXml)
    tree.write("config.xml")

The error i get when i pass cleanXml as parameter:

Traceback (most recent call last):
  File "app.py", line 45, in <module>
    tree.write("config.xml")
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py", line 817, in write
    self._root, encoding, default_namespace
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py", line 876, in _namespaces
    iterate = elem.getiterator # cET compatibility
AttributeError: 'unicode' object has no attribute 'getiterator'

Anybody knows how i can get my prettified xml to a file ? Thanks and Greetings!


Solution

  • The ElementTree constructor can be passed a root element and a file. To create an ElementTree from a string, use ElementTree.fromstring.

    However, that isn't what you want. Just open a file and write the string directly:

    with open("config.xml", "w") as config_file:
        config_file.write(cleanXml)