There is a class

class Point { public int X { get; set; } public int Y { get; set; } } 

I will serialize it directly into an XML file using the XmlSerializer,

 Point point = new Point(); XmlSerializer serializer = new XmlSerializer(typeof(Point)); StreamWriter writer = new StreamWriter(@"point.xml"); serializer.Serialize(writer, point); writer.Close(); 

How to serialize not directly into a file, but into a string (an object of type string)?

    2 answers 2

    Instead of StreamWriter you should use StringWriter :

      XmlSerializer serializer = new XmlSerializer(typeof(Point)); using( StringWriter writer = new StringWriter(...) ) { serializer.Serialize(writer,point); string serializedXML = writer.ToString(); } 
       public Form1() { InitializeComponent(); Point1 point = new Point1(); XmlSerializer serializer = new XmlSerializer(typeof(Point1)); using(MemoryStream stream = new MemoryStream()) { serializer.Serialize(stream, point); stream.Position = 0; TextReader reader = new StreamReader(stream); label1.Text = reader.ReadToEnd(); } } public class Point1 { public int X { get; set; } public int Y { get; set;} }