Refactor: consolidate code for writing xml to disk