Yesterday I asked how to replace text on a node with children using minidom.
Today I'm also trying to replace <node/>
with <node>text</node>
Unfortunately I'm feeling that my results are a horrible hack:
import xml.dom.minidom
from xml.dom.minidom import Node
def makenode(text):
n = xml.dom.minidom.parseString(text)
return n.childNodes[0]
def setText(node, newText):
if node.firstChild==None:
str = node.toxml();
n = len(str)
str = str[0:n-2]+'>'+newText+'</'+node.nodeName+'>' #DISGUSTINGHACK!
node.parentNode.replaceChild( makenode(str),node )
return
if node.firstChild.nodeType != node.TEXT_NODE:
raise Exception("setText: node "+node.toxml()+" does not contain text")
node.firstChild.replaceWholeText(newText)
def test():
olddoc = '<test><test2/></test>'
doc=xml.dom.minidom.parseString(olddoc)
node = doc.firstChild.firstChild # <test2/>
print "before:",olddoc
setText(node,"textinsidetest2")
newdoc = doc.firstChild.toxml()
print "after: ", newdoc
# desired result:
# newdoc='<test><test2>textinsidetest2</test2></test>'
test()
While the above code works, I feel it's a collossal hack. I've been poring through the xml.minidom documentation, and I'm not sure how else to do the above case, especially
without the hack marked #DISGUSTINGHACK!
above.