xml.dom.minidompython发行

2024-05-29 04:19:48 发布

您现在位置:Python中文网/ 问答频道 /正文

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;

给出以下错误:

^{pr2}$

Tags: fromtestimporttitleisxmlthisresp
3条回答

<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。在

因为不是文本节点,而是元素节点。包含“这是一个测试!”字符串实际上是这个元素节点的子节点。在

因此,您可以尝试以下操作(未测试,不假设文本节点的存在):

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

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

相关问题 更多 >

    热门问题