开发者

Write element value to an XML in Python

I have a text file containing a key=value pairs. I have another XML file which contains the "key" as "Source" Node and "value" as "Destination Node".

<message>
   <Source>key</Sou开发者_如何学编程rce>
   <Destination>value</Destination>
</message>

Suppose, I get a new text file containing the same keys but different values, how do I go about changing the XML file using the minidom ?

Can this be possible?


It would be easier to regenerate the XML file than to modify it in place:

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( ) )

This will print:

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

You could use e.g. configparser to read the file; you may have a better way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜