I have a XML file that I read with Python. I want to make some changes in the XML file and write it back out.
Here is my code:
from xml.dom.minidom import *
filename = "file.xml"
dom = xml.dom.minidom.parse(filename)
dicts = dom.getElementsByTagName("dict")
for dict in dictList:
keys = dict.getElementsByTagName("key")
for key in keys:
keyCData = key.firstChild.wholeText
if keyCData == "kind":
print keyCData #prints "kind"
key.firstChild.wholeText = "new text"
print key.firstChild.wholeText #prints "new text"
f = open("temp.xml", 'w')
dom.writexml(f)
f.close()
When I open “temp.xml” to look at though, all my elements with the “key” tag still have their CData as “kind” instead of “new text”. So how do I get the new data to be written out to the file?
Replace
with either
or
The key here is that
xml.dom.minidom.Text.wholeTextis a data descriptor, meant to be used more like a function than like an attribute. In fact, it collects data from nearby text and cdata nodes, in addition to its own data. Unfortunately, its setter doesn’t seem to be getting called, so by writing towholeText, you are overriding the function. Thewritexml()implementation, however, only looks at thedataattribute, notwholeText.This could be seen as a bug. In fact, someone could probably link
replaceWholeText()as the setter for thewholeTextproperty, but it may have to bypass the magic that the module uses to work with older versions of Python.