Python - 写Xml(格式化)

时间:2015-11-13 14:38:08

标签: python xml format elementtree prettify

我编写了这个python脚本以创建Xml内容,我想将这个“美化”的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送到文件中吗? 谢谢和问候!

1 个答案:

答案 0 :(得分:2)

ElementTree constructor可以传递根元素和文件。要从字符串创建ElementTree,请使用ElementTree.fromstring

但是,这不是你想要的。只需打开一个文件并直接写入字符串:

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