Hi Martin,
for elem in elem:
sort_and_indent(elem, level + 1)
I'd never write the above code — i.e. using the same variable name for the for loop's iterator as it's input. The ambiguity of what the "elem" variable refers too after this point feels too dangerous — I don't trust python's scoping rule to do what you expect.
Personally I would use,
for child_elem in elem:
sort_and_indent(child_elem, level + 1)
As a sanity check on this....
Gives the following output:
That final '5' shows Python's scoping isn't as tight as you hope.
Kind regards,
aid