RaphyTheGeek
RaphyTheGeek

Reputation: 115

Why the deserialization doesn't work?

I usually use the (de)serialization. I never had issues before, but I think it's just a human mistake I don't see... The serialization works perfect but not the deserialization.

Here my code:

using System;
using System.IO;
using System.Windows.Forms;
using Utils;

using System.Xml;
using System.Xml.Serialization;

namespace Tests
{
    public partial class MainForm : Form
    {
        private Test test;

        public MainForm()
        {
            InitializeComponent();
        }

        private void SaveButton_Click(object sender, EventArgs e)
        {
            try
            {
                test = new Test();
                test.MyInt = int.Parse(MyIntTextBox.Text);
                test.MyStr = MyStrTextBox.Text;
                test.Save();
                MessageBox.Show("Serialized!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Exception caught", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void LoadButton_Click(object sender, EventArgs e)
        {
            try
            {
                test = Test.Load();
                MyIntTextBox.Text = test.MyInt.ToString();
                MyStrTextBox.Text = test.MyStr;
                MessageBox.Show("Deserialized!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Exception caught", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

    }

    [Serializable]
    public class Test
    {
        public string MyStr { set; get; }
        public int MyInt { set; get; }

        public void Save()
        {
            using (StreamWriter sw = new StreamWriter("TestSerialized.xml"))
            {
                XmlSerializer xs = new XmlSerializer(typeof(Test));
                xs.Serialize(sw, this);
                sw.Flush();
            }
        }

        static public Test Load()
        {
            Test obj = null;
            using (StreamReader sr = new StreamReader("TestSerialized.xml"))
            {
                XmlSerializer xs = new XmlSerializer(typeof(Test));
                if (!xs.CanDeserialize(XmlReader.Create(sr)))
                    throw new NotSupportedException(string.Format("The file <{0}> cannot be loaded.", "TestSerialized.xml"));
                obj = (Test)xs.Deserialize(sr);
            }
            return (obj);
        }
    }
}

It's a basic form with 2 text boxes, one for each property of the Test class and 2 buttons, one for saving and the other one for loading.

Don't worry, I make sure to have a file to load ;)

I want to make a generic (de)serliazer class like:

public class Serializer<T>
{
    static public void Serialize(object obj, string path)
    {
        using (StreamWriter sw = new StreamWriter(path))
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            xs.Serialize(sw, obj);
            sw.Flush();
        }
    }

    static public T Dezerialize(string path)
    {
        T obj;
        using (StreamReader sr = new StreamReader(path))
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            if (!xs.CanDeserialize(XmlReader.Create(sr)))
                throw new NotSupportedException(string.Format("The file <{0}> cannot be loaded.", path));
            obj = (T)xs.Deserialize(sr);
        }
        return (obj);
    }
}

But I have the same issue: the deserialization doesn't work...

EDIT: I have an exception caught: "It exists an error in the XML document (0, 0)" And the XML document I want to deserialize (It's generated by the XmlSerializer)

<?xml version="1.0" encoding="utf-8"?>
<Test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <MyStr>toto</MyStr>
  <MyInt>45</MyInt>
</Test>

Thanks for helping !

Upvotes: 2

Views: 1546

Answers (3)

Dmytro
Dmytro

Reputation: 17196

Your code doesn't work because of this:

if (!xs.CanDeserialize(XmlReader.Create(sr)))
   throw new NotSupportedException(string.Format("The file <{0}> cannot be loaded.", "TestSerialized.xml"));

After this there is nothing to read anymore from sr and only then you are trying to deserialize - that's why it fails. Remove this code.

Upvotes: 1

Z .
Z .

Reputation: 12837

Take those 2 lines off

if (!xs.CanDeserialize(XmlReader.Create(sr))
    throw new NotSupportedException(string.Format("The file <{0}> cannot be loaded.", path));

or reset the stream after you check if can be deseralized

Upvotes: 2

HappyLee
HappyLee

Reputation: 455

http://social.msdn.microsoft.com/Forums/en-US/f5a5ff54-3743-400c-b14d-92dae95f3605/there-is-an-error-in-xml-document-0-0-error-while-xml-deserialization follow this link which has the exact reason and solution.

"After you have written to the stream it is positioned at the end, after the XML you have written. If you then try to read from that same stream there is no root element to be found. So you need to reposition the stream (stream.Position = 0) if the stream supports that or you need to close the stream once you have written to it and open a new one for reading."

Upvotes: 0

Related Questions