0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

And then doc.writexml(pythonfileobject) or something similar... docs.python.org/library/xml.dom.minidom.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.