in reply to XPATH Looping
Welcome to the monastery.
I doubt that the code you posted is part of whatever script "works fine". You have two instances of:
which should probably be
Please post a minimal example of code that reproduces your problem. These guidelines will help you in deciding how best to do this: How do I post a question effectively?