If you are sorting for display you dont need to sort and rebuild the XML tree at all. Just iterate over the node parent according to the X then Y attributes of the <location> child. If you
want to sort your file and save, then I think the simplest way would be to build a new tree and add in nodes as they are sorted. Then save your new xml tree over the top of the old.
I find Xpath easier to bend my mind around so I have been using XML::LibXML which gives you the option of mixing and matching between XPath and DOM according to the task.