One of our web-service we developed has a rather unique parameter: a well-formed XML document passed in a string format. Or, to put it in another way, a string parameter whose output written out in a file will become a well-formed XML document. There a variety of reasons for doing this, instead of say using an XmlDocument type, but that's really not important.
This presents an interesting problem: how DO you create an XML document and convert it into a string, hopefully without writing too much code?
As it turns out: not easy. We started out doing it the hard way: string concatenation. Boy, talk about doing things the hard way. Mal-formed XML, slow performance, etc. Yup, all the potential problems hit us one time or another.
Next, we moved to using StringBuilder. Performs better, but doesn't remove the problems of properly-formed XML.
Then, we improved to using XMLDocument. Finally, we're getting somewhere. But the solution is a little bit overkill, due to the fact we do not need to manipulate the XML document in any way before converting it into string.
Then, I stumbled upon using XMLWriter and StringWriter. Initially, I gave XMLWriter a pass because I mistakenly believed it can only be used to write to a file, and not to memory. Well, with StringWriter, you can. Problem solved!
Well, not quite. It turns out the StringWriter encoding is set to UTF-16, and there's no way to change it. Bummer.
In the end, I found the solution: use XMLTextWriter, MemoryStream and StreamReader. All this just to get the encoding just the way you want it. The solution is less elegant, but it IS less code than the rest of the solution mentioned that doesn't use XMLTextWriter, and it works. Sometimes, you just have to take some compromise. I know I'll be happier with this solution than the others. :)