Python - 写入 Xml(格式化)

Python - write Xml (formatted)

我编写此 python 脚本是为了创建 Xml 内容,我想将此 "prettified" xml 写入文件(已完成 50%):

到目前为止我的脚本:

    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")

将 cleanXml 作为参数传递时出现的错误:

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'

有人知道我如何将美化后的 xml 保存到文件中吗? 谢谢和问候!

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

然而,这不是你想要的。随便打开一个文件,直接写字符串:

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