tags:

views:

79

answers:

3
from xml.dom.minidom import *

resp = "<title> This is a test! </title>"

rssDoc = parseString(resp)

titles = rssDoc.getElementsByTagName('title')

moo = ""

for t in titles:
    moo += t.nodeValue;

Gives the following error:

main.py, line 42, in
       get moo += t.nodeValue;
TypeError: cannot concatenate 'str' and 'NoneType' objects
A: 

because t.nodeType is not equal to t.TEXT_NODE of course.

SilentGhost
+1  A: 

Because is not a text node, but an element node. The text node which contains the " This is a test! " string is actually a child node of this element node.

So you can try this (untested, not assumes existence of the text node):

if t.nodeType == t.ELEMENT_NODE:
    moo += t.childNodes[0].data
Frank
Thanks. Would be handy if elements had a .content member imho
tm1rbrt
+2  A: 

The <title> node contains a text node as a subnode. Maybe you want to iterate through the subnodes instead? Something like this:

from xml.dom.minidom import *

resp = "<title> This is a test! </title>"

rssDoc = parseString(resp)

titles = rssDoc.getElementsByTagName('title')

moo = ""

for t in titles:
    for child in t.childNodes:
        if child.nodeType == child.TEXT_NODE:
            moo += child.data
        else:
            moo += "not text "

print moo

For learning xml.dom.minidom you might also check out the section in Dive Into Python.

Nicholas Riley