3

I'm using XMLSerializer to serialize a class into a XML. There are plenty of examples to this and save the XML into a file. However what I want is to put the XML into a string rather than save it to a file.

I'm experimenting with the code below, but it's not working:

public static void Main(string[] args)
        {

            XmlSerializer ser = new XmlSerializer(typeof(TestClass));
            MemoryStream m = new MemoryStream();

            ser.Serialize(m, new TestClass());

            string xml = new StreamReader(m).ReadToEnd();

            Console.WriteLine(xml);

            Console.ReadLine();

        }

        public class TestClass
        {
            public int Legs = 4;
            public int NoOfKills = 100;
        }

Any ideas on how to fix this ?

Thanks.

Jonny
  • 2,787
  • 10
  • 40
  • 62

3 Answers3

10

You have to position your memory stream back to the beginning prior to reading like this:

        XmlSerializer ser = new XmlSerializer(typeof(TestClass));
        MemoryStream m = new MemoryStream();

        ser.Serialize(m, new TestClass());

        // reset to 0 so we start reading from the beginning of the stream
        m.Position = 0;
        string xml = new StreamReader(m).ReadToEnd();

On top of that, it's always important to close resources by either calling dispose or close. Your full code should be something like this:

        XmlSerializer ser = new XmlSerializer(typeof(TestClass));
        string xml;

        using (MemoryStream m = new MemoryStream())
        {
            ser.Serialize(m, new TestClass());

            // reset to 0
            m.Position = 0;
            xml = new StreamReader(m).ReadToEnd();
        }

        Console.WriteLine(xml);
        Console.ReadLine();
Polity
  • 14,734
  • 2
  • 40
  • 40
1

There's the [Serializabe] attribute missing on class TestClass and you have to set the position of the memory stream to the beginning:

         XmlSerializer ser = new XmlSerializer(typeof(TestClass));
        MemoryStream m = new MemoryStream();
        ser.Serialize(m, new TestClass());
        m.Position = 0;
        string xml = new StreamReader(m).ReadToEnd();
        Console.WriteLine(xml);
        Console.ReadLine();
Fischermaen
  • 12,238
  • 2
  • 39
  • 56
-4

Your memory stream is not closed, and is positioned at the end (next available location to write in). My guess is that you must Close it, or Seek to its beginning. The way you do you don't read anything because you are already at the end of stream. So add Seek() after you serialize objects. Like this:

        XmlSerializer ser = new XmlSerializer(typeof(TestClass));
        MemoryStream m = new MemoryStream();

        ser.Serialize(m, new TestClass());

        m.Seek(0, SeekOrigin.Begin);   //<-- ADD THIS!

        string xml = new StreamReader(m).ReadToEnd();

        Console.WriteLine(xml);

        Console.ReadLine();
Cipi
  • 11,055
  • 9
  • 47
  • 60