Python 中 Element.tagName 无法正常工作

2 投票
3 回答
2730 浏览
提问于 2025-04-17 07:04

我在Django里写了以下代码,但它返回了一个关于 tagName 属性的错误:

def _parse_google_checkout_response(response_xml):
    redirect_url=''
    xml_doc=minidom.parseString(response_xml)
    root = xml_doc.documentElement
    node=root.childNodes[1]
    if node.tagName == 'redirect-url':
        redirect_url=node.firstChild.data
    if node.tagName == 'error-message':
        raise RuntimeError(node.firstChild.data)
    return redirect_url

这是错误的反馈信息:

Exception Type: AttributeError
Exception Value:    
Text instance has no attribute 'tagName'

有没有人知道这是怎么回事?

3 个回答

0

在childNodes这个列表中,第一个项目(childNodes[0])是文本内容。第一个子元素从childNodes的第1个项目开始。

在下面的图片中,你可以看到第0项旁边有{instance} Text,表示它是文本项。下面的第1项有{instance} Element,表示它是一个元素项。

你还可以看到childNodes[0]有一个属性叫'wholeText'(表示文本内容),而childNodes的第1项有一个属性叫'tagName',这是第一个子元素的名称。所以你不能从childNodes[0]获取tagName这个属性。

childNodes项目零和一的示例

1
node=root.childNodes[1]

node 是一个 DOM 文本节点。它没有 tagName 属性。

>>> d = xml.dom.minidom.parseString('<root>a<node>b</node>c</root>')
>>> root = d.documentElement
>>> nodes = root.childNodes
>>> for node in nodes:
...   node
...
<DOM Text node "u'a'">
<DOM Element: node at 0xb706536c>
<DOM Text node "u'c'">

在上面的例子中,文档元素('root')有 3 个子节点。

第一个是一个文本节点,它没有 tagName 属性。

相反,它的内容可以通过 'data' 属性来访问:root.childNodes[0].data

第二个是一个元素,它包含其他节点。这种类型的节点有 tagName 属性。

第三个节点和第一个节点类似。

1

你需要看看你收到的xml文件。问题可能是你不仅在根节点里得到了标签,还有一些文本。

举个例子:

>>> xml_doc = minidom.parseString('<root>text<tag></tag></root>')
>>> root = xml.documentElement
>>> root.childNodes
[<DOM Text node "u'root node '...">, <DOM Element: tag at 0x2259368>]

注意,在我的例子中,第一个节点是一个文本节点,第二个节点是一个标签。所以,root.childNodes[0].tagName 会引发和你遇到的同样的错误,而root.childNodes[1].tagName 则会正常返回 tag,就像你预期的那样。

撰写回答