I'm too lazy right now to sort through your XML to figure out exactly how you want to do the structure-- rather than just turning each line into an XML record it looks like you want a bunch of nested loops following the columns almost from left to right, and terminating each loop when there's a change in the value. That should be pretty straightforward.
You should be able to use Text::CSV and XML::LibXML to do something that runs pretty fast. You can probably get by with focusing on the XML::LibXML::Node and XML::LibXML::Element docs.
And before you get too far- have you profiled your code at all to see where the hangups are? Is it the SQL being super slow because you don't have it indexed on the right columns and while the perl might turn the CSV into XML in a second or two, you're going to spend 3 days exporting the SQL to CSV in the sorted format you show here?