开发者

xml.dom.minidom python issue

开发者 https://www.devze.com 2022-12-13 23:39 出处:网络
from xml.dom.minidom import * resp = \"<title> This is a test! </title>\" rssDoc = parseString(resp)
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

精彩评论

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