After looking at the docs, I think you're shooting yourself in the foot by using keyattr. It's converting what would have been an array into a hash. Since elements of a hash are not ordered, using keyattr is causing you to lose the order of your XML records.