views:

46

answers:

1

HI,

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</Source>
   <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 ?

Thanks!

+1  A: 

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.

katrielalex
And then `doc.writexml(pythonfileobject)` or something similar... http://docs.python.org/library/xml.dom.minidom.html
Skilldrick
Thanks all for the replies.
RMR