我對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>
標籤發現的數量,但事實並非如此。爲什麼是這樣?
嘗試'textCollection.length' – Torious 2012-04-15 03:10:37