I've never used XMPie so I won't be much help with the nuts and bolts, but maybe can help with the logic. In the data, is 1 always populated, and if there are 2 teacher/courses, is it always going to be 1 and 2, or will it be random like possibly 3 and 6?
I use SmartStream and it has an easy way for me to tell it that if the variables are empty to not include any static copy on that line (like commas.)