Thanks Mart, that's really kind! To cut a long story short, I eventually figured out that I don't need to manipulate any XML itself at this stage, I can manipulate everything first and just render it at the end.
I've wasted so much time messing around, so if it gets complicated for me again, I'll come and ask! Sometimes the obvious is the most elusive! Best wishes, -D