在Python中将元素值写入XML

时间:2010-08-23 11:22:42

标签: python xml minidom

我有一个包含key = value对的文本文件。我有另一个XML文件,其中包含“key”作为“Source”节点,“value”作为“Destination Node”。

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

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

这可能吗?

1 个答案:

答案 0 :(得分: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阅读文件;你可能有更好的方法。

相关问题