[Tutor] help request from a newbie w/ problems parsing XML
Magnus Lyckå
magnus@thinkware.se
Wed Jun 4 18:44:01 2003
I've never really used dom, but let's take a look...
At 17:38 2003-06-04 -0400, Andy Osagie wrote:
>Hello,
>I seem to have trouble editing the values of parsed XML documents so that I
>can save them with my new values.
>
> >>> from xml.dom import minidom
> >>> doc = minidom.parseString("<entry>random stuff</entry>")
> >>> doc.childNodes[0].toxml()
>u'<entry>random stuff</entry>'
> >>> doc.childNodes[0].nodeName
>u'entry'
> >>> doc.childNodes[0].nodeValue
As you see here, nothing was printed. I.e. .nodeValue is not "random stuff".
doc.childNodes[0].nodeValue is None, but doc.childNodes[0] has a childNode!
>>> doc.childNodes[0].childNodes[0].toxml()
u'random stuff'
That's what you want to replace, right? Not nodeValue. But you can't simply
set that to a string, since it isn't a string.
>>> type(doc.childNodes[0].childNodes[0])
<type 'instance'>
>>> doc.childNodes[0].childNodes[0].__class__
<class xml.dom.minidom.Text at 0x012DA878>
Aha, let's try to use that!
>>> doc.childNodes[0].replaceChild(minidom.Text('test value'),
doc.childNodes[0].childNodes[0])
<DOM Text node "random stu...">
>>> doc.toxml()
u'<?xml version="1.0" ?>\n<entry>test value</entry>'
Is this what you wanted? Note that a Text node in the DOM isn't
just a string. It's an instance of a class.
In Python, a name on the left hand side of an assignment is just
a pointer to an object, so if you do...
x = 'test value'
...x will certainly be a name for a string object, even if it
happened to refer to a xml.dom.minidom.Text instance before.
Names aren't typed in Python, only the objects they refer to
are typed.
--
Magnus Lycka (It's really Lyckå), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language