Top.Mail.Ru
Python
? ?
LiveJournal for python.
View:Personal Journal.
View:Friends.
View:Calendar.
Missed some entries? Then simply jump to the previous day or the next day.

Tuesday, May 25th, 2004

Subject:Weird python DOM behavior
Time:2:22 pm.
Trying to learn DOM. Can't quite figure out how this is supposed to work though.
I can't change the elements, so I create a new one, grab the old one's children and then call the parents replaceChild method. Seems straightforward, right?

""" a simple test case showing how to replace an element with another
while still keeping the child nodes of the replaced element.
"""
import xml.dom.minidom
from xml.dom.minidom import Element, parseString
funXmlString = "<p> a para with <b> bold </b> inside</p>"
funXmlDoc = parseString(funXmlString)
testElement=funXmlDoc.documentElement
print "testElement: " + testElement.toxml()
para = Element("para")
for child in testElement.childNodes:
    para.appendChild(child)
print "para after adopting: " + para.toxml()

# For some reason,  we lose the entire <b>..</b> part! 
# Where did it go?
assert para.toxml() ==  "<para> a para with <b> bold </b> inside</para>"

funXmlDoc.replaceChild(para, testElement)
print "funXmlDoc after replacement:" + funXmlDoc.toxml();


Here is the output:

testElement: <p> a para with <b> bold </b> inside</p>
para after adopting: <para> a para with  inside</para>
Traceback (most recent call last):
  File "testdom.py", line 18, in ?
    assert para.toxml() ==  "<para> a para with <b> bold </b> inside</para>"
AssertionError
Comments: Read 9 orAdd Your Own.

LiveJournal for python.

View:User Info.
View:Friends.
View:Calendar.
View:Memories.
Missed some entries? Then simply jump to the previous day or the next day.

Image