[英]Write element value to an XML in Python
我有一個包含key = value對的文本文件。 我有另一個XML文件,其中包含“鍵”作為“源”節點,而“值”作為“目標節點”。
<message>
<Source>key</Source>
<Destination>value</Destination>
</message>
假設我得到一個包含相同鍵但值不同的新文本文件,如何使用minidom更改XML文件?
這有可能嗎?
重新生成XML文件要比在適當位置修改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
讀取文件; 您可能有更好的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.