它會更容易重新生成XML文件,而不是在地方進行修改:
from xml.dom.minidom import Document
doc = Document()
root = doc.createElement("root")
for key, value in <some iterator>:
message = doc.createElement("message")
source = doc.createElement("Source")
source.appendChild(doc.createTextNode(key))
dest = doc.createElement("Destination")
dest.appendChild(doc.createTextNode(value))
message.appendChild(source)
message.appendChild(dest)
root.appendChild(message)
doc.appendChild(root)
print(doc.toprettyxml())
這將打印:
<root>
<message>
<Source>
key
</Source>
<Destination>
value
</Destination>
</message>
</root>
你可以使用例如configparser
來讀取文件;你可能有更好的方法。
然後'doc.writexml(pythonfileobject)'或類似的東西... http://docs.python.org/library/xml.dom.minidom.html – Skilldrick 2010-08-23 11:45:18
感謝所有的答覆。 – RMR 2010-08-24 05:52:41