2015-11-13 56 views
1

我爲了創建XML內容寫這個python腳本,我想這種「美化」 XML寫(50%完成)文件:Python的 - 編寫XML(格式化)

我的劇本至今:

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

ElementTree constructor可以傳遞一個根元素和一個文件。要從字符串創建ElementTree,請使用ElementTree.fromstring

但是,這不是你想要的。只需打開一個文件並直接寫入字符串:

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

非常感謝!作品! :) –