Tag Archives: stringwriter

Using StringWriter with XmlWriter

So how to use the StringWriter with XmlWriter to get XML string form the writer without going through IO. You need to use some writer object to make it produce XML – but don’t need to serialize this to disk. How to do this?

  1. First you need a StringWriter (sw) object.
  2. The a XmlWriter is created with by sending the sw as input to the constructor of XmlWriter.
  3. Then use the XmlWriter
  4. Now you need to flush the sw. Call close on the StringWriter
  5. And close the XmlWriter
  6. Then you get the XML from the sw.ToString method.

StringWriter sw = new StringWriter();
var writer = XmlWriter.Create(sw);
DoXml(writer);
sw.Close();
//Don't need to do this writer.Close();
Console.WriteLine("returned with sw:" + sw.ToString());