2010-08-23 90 views
0

我有一个包含key = value对的文本文件。我有另一个XML文件,其中包含“关键字”作为“源”节点和“值”作为“目标节点”。将元素值写入Python中的XML

<message> 
    <Source>key</Source> 
    <Destination>value</Destination> 
</message> 

假设,我得到一个新的文本文件包含相同的键但不同的值,我该如何去改变使用minidom XML文件?

这可能吗?

回答

2

它会更容易重新生成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来读取文件;你可能有更好的方法。

+0

然后'doc.writexml(pythonfileobject)'或类似的东西... http://docs.python.org/library/xml.dom.minidom.html – Skilldrick 2010-08-23 11:45:18

+0

感谢所有的答复。 – RMR 2010-08-24 05:52:41