littleO
littleO

Reputation: 33

Why do I get this error at XML Deserialization function?

I have created two functions, XML serialize and deserialize. The problem is that I get an error on derserialization. Below you may find the functions:

public string Serialize(Object o)
{
    using (var writer = new StringWriter())
    {
        new XmlSerializer(o.GetType()).Serialize(writer, o);
        return writer.ToString();
    }
}

public PathDetailsMessage Deserialize(string xml)
{
    using (TextReader reader = new StringReader(xml))
    {
         XmlSerializer serializer = new XmlSerializer(typeof(PathDetailsMessage));
         return (PathDetailsMessage)serializer.Deserialize(reader);
    }
}

And the calls:

static void Main(string[] args)
{
    PathDetailsBLL train = new PathDetailsBLL();
    PathDetailsMessage pdm = train.GetDetails();
    string xml = train.Serialize(pdm);
    PathDetailsBLL dsa = new PathDetailsBLL();
    PathDetailsMessage fds = new PathDetailsMessage();
    fds = dsa.Deserialize(pdm.ToString());
    Console.Write(fds);
    Console.ReadKey();
}

On the line return (PathDetailsMessage)serializer.Deserialize(reader); I get the following error:

System.InvalidOperationException: 'There is an error in XML document (1, 1).'

XmlException: Data at the root level is invalid. Line 1, position 1.

Can you help me?

Thank you.

Upvotes: 0

Views: 731

Answers (2)

Alex Riveron
Alex Riveron

Reputation: 411

It seems that you're serializing the object returned by train.GetDetails() into an XML string, xml, but you're trying to deserialize the string (not necessarily an XML string) returned by pdm.ToString(). Did you, instead, intend to call dsa.Deserialize(xml)?

Upvotes: 1

vadim
vadim

Reputation: 1726

 fds = dsa.Deserialize(pdm.ToString());

You want to deserialize xml variable but using pdm.ToString() instead. Try

 fds = dsa.Deserialize(xml);

Upvotes: 1

Related Questions