2009-12-16 2 views
0
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; 

다음과 같은 오류를 제공합니다 :xml.dom.minidom 파이썬 문제

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

답변

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 

당신은 또한 section in Dive Into Python 확인 할 수 xml.dom.minidom 학습하십시오.

0

t.nodeType 때문에 물론 t.TEXT_NODE 동일하지 않습니다.

1

텍스트 노드가 아니기 때문에 요소 노드입니다. "This is a test!"문자열을 포함하는 텍스트 노드는 실제로이 요소 노드의 자식 노드입니다.

그래서 당신은 (안된 아닌 텍스트 노드의 존재를 가정)이 시도 할 수 있습니다 :

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

감사합니다. 요소에 .content 멤버가있는 경우 편리 할 것입니다. imho –