2012-04-15 230 views
3

我對Python很陌生,試圖編寫解析某些XML的程序。我遇到了這個問題,當我嘗試撥打.len()時,我認爲它是NodeList,我得到錯誤'NodeList' object has no attribute 'len'。這真是令我感到詫異,因爲documentation說:在Python中解析XML和我的'NodeList'對象沒有屬性'len'

此外,Python的DOM接口需要一些額外的支持,以允許使用像Python序列節點列表對象。所有節點列表的實現必須包括LEN()支持

這裏是我的代碼:

import xml.dom.minidom 

def testFunction(translationDOM): 
    textCollection = translationDOM.getElementsByTagName("onscreen_text") 
    for onscreenText in textCollection: 
     print textCollection.len() 

然後在Main() ...

translationDom = parse(xmlFileName) 
testFunction(translationDom) 

我不想發佈我的整個xml在這裏(其龐大),但有一些塊類似於:

<onscreen_text> 
    <source id="2036" unique_name="blah" should_be_translated="True"> 
    .... 
</onscreen_text> 

以下是完整的錯誤文本:

File "trophytool.py", line 155, in <module> 
    main() 
    File "trophytool.py", line 134, in main 
    testFunction(translationDom) 
    File "trophytool.py", line 64, in testFunction 
    print textCollection.len() 
AttributeError: 'NodeList' object has no attribute 'len' 

你會認爲它會打印<onscreen_text>標籤發現的數量,但事實並非如此。爲什麼是這樣?

+0

嘗試'textCollection.length' – Torious 2012-04-15 03:10:37

回答

1

試試這個:

print len(textCollection) 

說明:支持len通常意味着一個類實現了__len__()方法(不len()),這反過來又可以讓你打電話len(object)

+0

剛剛經過測試,它的工作原理。謝謝。 – mukmuk64 2012-04-15 03:14:15

+0

很好聽。不要忘記接受(10分鐘後) – 2012-04-15 03:15:31

1

getElementsByTagName()方法總是返回一個列表,即使只有一個項目。 例如,在接下來的XML

<school> 
    <department /> 
</school> 

如果你有指向「學校」的標籤,你叫

myNode.getElementsByTagName("department") 

它會返回lenght的節點列表中的一個

如果您確定調用方法getElementsByTagName()將只返回一個項目,您可以執行此操作而不是上述語句

myNode.getElementsByTagName("department").item(0) 

它將返回一個單一節點而不是隻有一個節點的節點列表。

相關問題