python的Element.tagName不起作用

时间:2011-11-25 22:18:12

标签: python xml django

我在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 :(得分: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

答案 1 :(得分:1)

node=root.childNodes[1]

node是DOM Text节点。它没有tagName属性。 e.g。

>>> 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属性。 相反,它的内容可以通过“数据”属性访问:root.childNodes[0].data

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

第三个类似于第一个。

答案 2 :(得分:0)

childNodes(childNodes [0])中的第一项是文本。第一个子元素从childNodes第1项开始。

在下图中,您可以看到项目0旁边有{instance}文本 - 因为它是文本项目。在下面,第1项有{instance}元素,因为它是一个元素项。

您还可以看到childNodes [0]具有属性&#39; wholeText&#39; (表示文本)而childNodes项1具有属性&#39; tagName&#39;,这是第一个子元素的名称。因此,您无法尝试将tagName属性从childNodes [0]中删除。

Example of childNodes items zero and one