1

I found some discussion in same topic but still can't find the ultimate solution to a very simple task of serialize/deserialze an object in xml format.

The issue I run into is :

There is an error in XML document (2,2)

enter image description here

And the code to reproduce issue :

  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void Serialize_Click(object sender, EventArgs e)
    {
      testclass t = new testclass();
      t.dummyInt = 10;
      t.dummyString = "sssdf";
      textBox1.Text = t.SerializeObject();
    }

    private void Deserialize_Click(object sender, EventArgs e)
    {
      try
      {
        object o = MySerializer.DeserializeObject<object>(textBox1.Text);
      }
      catch (Exception Ex)
      {
        MessageBox.Show(Ex.Message + Ex.InnerException, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
    }
  }

public class testclass
{
  public int dummyInt;
  public string dummyString;
  public testclass() { }
}

public static class MySerializer
{
  public static string SerializeObject<T>(this T toSerialize)
  {
    XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
    using (StringWriter textWriter = new StringWriter())
    {
      xmlSerializer.Serialize(textWriter, toSerialize);
      return textWriter.ToString();
    }
  }

  public static T DeserializeObject<T>(string data)
  {
    XmlSerializer serializer = new XmlSerializer(typeof(T));

    using (StringReader sReader = new StringReader(data))
    {
      return (T)serializer.Deserialize(sReader);
    }
  }
}

So what is wrong here?

Community
  • 1
  • 1

1 Answers1

2

You are calling Deserialize with the wrong type.

This will build you a serializer to return an object from XML.

var o = MySerializer.DeserializeObject<object>(xml);

To have the above line not bark its xml input should look like:

<?xml version="1.0" encoding="utf-16"?>
<anyType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />

If you want to return a testclass tell the serializer to do so:

var tc = MySerializer.DeserializeObject<testclass>(xml);

That will give you a testclass instance with your xml input (if I fix the errors in it)

rene
  • 41,474
  • 78
  • 114
  • 152
  • Thank you, you're perfectly right, however I have trouble with the solution as I usually don't know upfront what object type I am going to deserialize. I would need to also save the object type name and use reflection to get the type back before deserialization. That's annoying... –  Dec 21 '17 at 12:16
  • Yeah, you have to know the type, but you could peek in the xml at the first nodename to *guess* the type. Still a guess though ... – rene Dec 21 '17 at 12:19
  • that's going to be the type name only, I will still need reflection to get Type. But no issues, already working this way :-) –  Dec 21 '17 at 12:31