XmlWriter to Write to a String Instead of to a File

前端 未结 6 2017
星月不相逢
星月不相逢 2020-11-27 03:59

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         


        
6条回答
  •  独厮守ぢ
    2020-11-27 04:31

    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();
    }
    

提交回复
热议问题