If for all x
in Root
, x.tag == 'ecuID'
is True
but x.get('id') == '16'
is not True
, then the loop never reaches a return
statement, and None
is returned instead.
This also happens when Root
is an empty sequence, like for any leaf element in your node tree.
If any <ecuID id="16">
node is encountered where there is no node
attribute, then None
is returned as well, as x.get('corner')
would return the default instead.
Instead of recursing, why not use a stack approach?
def traverse(node):
stack = [node]
while stack:
next = stack.pop()
for node in next:
if node.tag == 'ecuID' and node.get('id') == '16':
return node.get('corner')
stack.append(node)
This'll traverse the tree as well, visiting all nodes until your node is found or None
is returned when there is no matching node.
Best of all would just to be the getiterator()
method:
def traverse(root):
for node in root.getiterator('ecuID'):
if node.get('id') == '16':
return node.get('corner')