factor out xml building and remove duplication