0

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.

littleO
  • 33
  • 6
  • Does this answer your question? [Deserialization error in XML document(1,1)](https://stackoverflow.com/questions/4726208/deserialization-error-in-xml-document1-1) – Trevor Feb 25 '21 at 12:37
  • You may have a namespace issue if the tag on first row has a namespace. – jdweng Feb 25 '21 at 12:56

2 Answers2

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

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

 fds = dsa.Deserialize(xml);
vadim
  • 1,698
  • 1
  • 10
  • 19
  • Thanks! I was rushing and it seems that I used the wrong variable. This helped me to solve the issue. – littleO Feb 26 '21 at 06:37
1

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)?

Alex Riveron
  • 389
  • 1
  • 10