Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Class to XML to string

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.

like image 918
Jonny Avatar asked Jun 22 '26 09:06

Jonny


2 Answers

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();
like image 159
Polity Avatar answered Jun 23 '26 22:06

Polity


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();
like image 23
Fischermaen Avatar answered Jun 23 '26 22:06

Fischermaen