Anyone who is concerned about licensing ambiguity when reusing code snippets from stack overflow may be interested in the following 3-clause BSD-licensed code, which appears to do what is requested by the original poster:
http://lenzconsulting.com/xml-to-string/