2016-09-05 50 views
0

將編輯的XML根文件寫入新文件最簡單的方法是什麼?這是我到目前爲止,它的投擲AttributeError:'模塊'對象沒有屬性'寫'
PS:除了ElementTree我不能使用任何其他api。ElementTree寫入XML

import xml.etree.ElementTree as ET 
from xml.etree.ElementTree import Element, SubElement, Comment 
from ElementTree_pretty import prettify 
tree = ET.parse('file-to-be-edited.xml') 
root = tree.getroot() 

#Process XML here 

ET.write('file-after-edits.xml') 

回答

1

您的treeElementTree對象,它提供了一個write()方法來編寫樹。例如:

#Process XML here 
tree.write('file-after-edits.xml', encoding='utf8') 
+0

感謝您的解決方案。愚蠢的錯誤在我的角色。有什麼方法可以美化生成的文件? – user1195192

+0

您可以使用['lxml'](http://lxml.de/),它提供了一個與ElementTree兼容的API。它的'tree.write()'方法接受'pretty_print = True'參數。 – mhawke

+0

或者使用'minidom',參見:http://stackoverflow.com/questions/749796/pretty-printing-xml-in-python – mhawke

0

AttributeError的:「模塊」對象有沒有屬性「寫」是說,你不能直接從ElementTree的類調用write方法,它不是一個靜態的方法,嘗試使用tree.write('file-after-edits.xml'),樹是你的對象來自ElementTree。

+0

無論如何可以美化生成的文件? – user1195192