2011-11-25 22 views
2

,我有以下的Django的代碼和它返回約tagName屬性的錯誤:Element.tagName爲Python不工作

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' 

任何人都有一個線索到這裏發生了什麼?

回答

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引發了與您相同的例外情況,而僅按預期返回tag

0
node=root.childNodes[1] 

節點是一個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屬性。 第三個與第一個類似。

0

childNodes(childNodes [0])中的第一項是文本。第一個子元素從childNodes項目1開始。

在下圖中,您可以看到項目0的{實例}文本旁邊 - 因爲它是文本項目。在此之下,項目1具有{實例}元素,因爲它是元素項目。

您還可以看到childNodes [0]具有屬性'wholeText'(表示文本),而childNodes項目1具有屬性'tagName',它是第一個子元素的名稱。所以你不能嘗試將tagName屬性關閉childNodes [0]。

Example of childNodes items zero and one