xml.dom.minidom python问题

时间:2009-12-16 10:06:09

标签: python xml

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;

给出以下错误:

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

3 个答案:

答案 0 :(得分:2)

<title>节点包含一个文本节点作为子节点。也许你想迭代子节点?像这样:

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

要学习xml.dom.minidom,您还可以查看section in Dive Into Python

答案 1 :(得分:1)

因为它不是文本节点,而是元素节点。包含“This is a test!”字符串的文本节点实际上是此元素节点的子节点。

所以你可以尝试这个(未经测试,不假设存在文本节点):

if t.nodeType == t.ELEMENT_NODE:
    moo += t.childNodes[0].data

答案 2 :(得分:0)

因为t.nodeType当然不等于t.TEXT_NODE