I’m very new to Python and trying to write a program that parses some XML. I’m having the issue where when I attempt to call .len() on what I believe to be a NodeList I get the error 'NodeList' object has no attribute 'len'. This is really surprising to me because the documentation says:
In addition, the Python DOM interface requires that some additional support is provided to allow NodeList objects to be used as Python sequences. All NodeList implementations must include support for len()
Here’s my code:
import xml.dom.minidom
def testFunction(translationDOM):
textCollection = translationDOM.getElementsByTagName("onscreen_text")
for onscreenText in textCollection:
print textCollection.len()
and then in the Main()…
translationDom = parse(xmlFileName)
testFunction(translationDom)
I don’t want to post my entire xml here (its massive), but there’s a number of blocks similar to:
<onscreen_text>
<source id="2036" unique_name="blah" should_be_translated="True">
....
</onscreen_text>
Here’s the full error 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'
You’d think it would print the number of <onscreen_text> tags it finds, but it doesn’t. Why is this?
Try this instead:
Explanation: Support for
lenusually means a class implements the__len__()method (notlen()), which in turn allows you to calllen(object).