Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

There is an error in XML document (1, 41)

When i am doing Deserialize of xml i am getting "There is an error in XML document (1, 41)." . Can anyone tell me about what is the issue is all about.

 public static T DeserializeFromXml<T>(string xml)
        {
            T result;
            XmlSerializer ser = new XmlSerializer(typeof(T));
            using (TextReader tr = new StringReader(xml))
            {
                result = (T)ser.Deserialize(tr);
            }
            return result;
        }

I use this function to do it.

<?xml version='1.0' encoding='utf-16'?>
<Message>
<FirstName>Hunt</FirstName>
<LastName>DAvid</LastName>
</Message>
like image 729
Pradeep Avatar asked Mar 22 '12 11:03

Pradeep


People also ask

What does error in XML document mean?

An error was detected while trying to load an XML schema file. This normally means that there was a problem locating the document (either the document does not exist or there is a problem with permissions) or that the schema itself is in error.

What is XML serialization and Deserialization in C#?

Serialization is a process by which an object's state is transformed in some serial data format, such as XML or binary format. Deserialization, on the other hand, is used to convert the byte of data, such as XML or binary data, to object type.


1 Answers

Ensure your Message class looks like below:

[Serializable, XmlRoot("Message")]
public class Message
{
    public string FirstName { get; set; }

    public string LastName { get; set; }
}

This works for me fine:

string xml = File.ReadAllText("c:\\Message.xml");
var result = DeserializeFromXml<Message>(xml);

MSDN, XmlRoot.ElementName:

The name of the XML root element that is generated and recognized in an XML-document instance. The default is the name of the serialized class.

So it might be your class name is not Message and this is why deserializer was not able find it using default behaviour.

like image 172
sll Avatar answered Sep 18 '22 05:09

sll