2

I am relatively new to python and having trouble some trouble looping over a nodes children using xml.dom. I want to do this:

dom = parse("synth_options.xml")
root = dom.documentElement
child_nodes = root.childNode

for index, node in child_nodes:
    #do stuff with index and node

However, I get this error:

Traceback (most recent call last):
  File "synth.py", line 142, in <module>
    for index, node in child_nodes:
TypeError: iteration over non-sequence

Strangely, this works:

for node in child_nodes:
    #do stuff with index and node

I can post more code if it would be helpful, but I don't think there is anything else relevant. Thanks in advance.

1 Answer 1

4

If you want to get both the index and the value, you can use enumerate:

for index, node in enumerate(child_nodes):

enumerate returns a tuple of the list indices and values.

Example of use:

>>> l = ['a', 'b', 'c']
>>> for index, value in enumerate(l):
    print index, value


0 a
1 b
2 c

Hope this helps!

Sign up to request clarification or add additional context in comments.

1 Comment

I can't accept your answer yet, but this works. Why exactly is this necessary?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.