I have a WCF service that needs to return a string of XML. But it seems like the writer only wants to build up a file, not a string. I tried:
string nextXM
As Richard said, StringWriter
is the way forward. There's one snag, however: by default, StringWriter
will advertise itself as being in UTF-16. Usually XML is in UTF-8. You can fix this by subclassing StringWriter;
public class Utf8StringWriter : StringWriter
{
public override Encoding Encoding
{
get { return Encoding.UTF8; }
}
}
This will affect the declaration written by XmlWriter
. Of course, if you then write the string out elsewhere in binary form, make sure you use an encoding which matches whichever encoding you fix for the StringWriter
. (The above code always assumes UTF-8; it's trivial to make a more general version which accepts an encoding in the constructor.)
You'd then use:
using (TextWriter writer = new Utf8StringWriter())
{
using (XmlWriter xmlWriter = XmlWriter.Create(writer))
{
...
}
return writer.ToString();
}