[Tutor] Writing to XML file with minidom

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Aug 22 19:57:36 CEST 2005

> """ Parse the xml file """
>             xmlDocument = minidom.parse(self.configFile)
[code cut]

> Now I want to change a string that a retrieved from the file and write
> it back to where it was. So, I get something, change it and write it
> back.
> How do I put the new string in the place of the old? How do I overwrite
> the first value with the new value?

Hi Johan,

The documentation in:


has a small example where they insert text into an element:

###### (From the documentation)
from xml.dom.minidom import getDOMImplementation
impl = getDOMImplementation()
newdoc = impl.createDocument(None, "some_tag", None)
top_element = newdoc.documentElement
text = newdoc.createTextNode('Some textual content.')

Elements have methods like appendChild(), replaceChild() and
removeChild().  So it should be fairly straightforward to replace the
existing text node with a new one.

That being said, the DOM model is a bit verbose and feels very low-level.
Have you looked at the third-party "ElementTree" module yet?


It's a bit more convenient to work with; its model maps better to Python.

Good luck!

More information about the Tutor mailing list