开发者

xml.dom.minidom python issue

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


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜