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"开发者_如何学C
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
key.firstChild.wholeText = "new text"
with either
key.firstChild.replaceWholeText("new text")
or
key.firstChild.data = "new text"
The key here is that xml.dom.minidom.Text.wholeText
is 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 to wholeText
, you are overriding the function. The writexml()
implementation, however, only looks at the data
attribute, not wholeText
.
This could be seen as a bug. In fact, someone could probably link replaceWholeText()
as the setter for the wholeText
property, but it may have to bypass the magic that the module uses to work with older versions of Python.
You must do a node replace
from xml.dom.minidom import *
filename = "file.xml"
dom = xml.dom.minidom.parse(filename)
dictList = dom.getElementsByTagName("dict")
for dict in dictList:
keys = dict.getElementsByTagName("key")
for key in keys:
keyCData = key.firstChild.wholeText.strip() // clean
if keyCData == "kind":
new_text = dom.createTextNode('new text') // new textnode
key.replaceChild(new_text, key.firstChild) // replace old
f = open("temp.xml", 'w')
dom.writexml(f)
f.close()
精彩评论