Minor point: since `xml_writer` is used so many times in this function, it obscures the actually "goings on" a little.  Maybe just call it `w`?