Search code examples
c#xmldeserializationxml-deserialization

C# xml to object (deserialization)


XML to C# object returning error:

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

How to deserialize xml string to c# object?

Here is my XML:

<MSGIDRETURN>
    <VERSION>1.0</VERSION>
    <MSGID_LIST>
        <MSGID>Test1234567</MSGID>
    </MSGID_LIST>
</MSGIDRETURN>

Here is my C# Classes:

[XmlRoot("MSGIDRETURN")]
public class MSGIDRETURN
{
    [XmlElement("VERSION")]
    public string Version { get; set; }

    [XmlElement("MSGID_LIST")]
    public MSGID_LIST MsgIdList { get; set; }
}

[Serializable()]
public class MSGID_LIST
{
    [XmlElement("MSGID")]
    public List<string> MsgId { get; set; }
}

And Deserialization Code :

XmlSerializer serializer = new XmlSerializer(typeof(MSGIDRETURN));
        StringReader rdr = new StringReader(inputString.Trim());
        MSGIDRETURN resultingMessage = (MSGIDRETURN)serializer.Deserialize(rdr);

Solution

  • Just tried your solution, with string instead of input and it's working. What is your inputString? Is that file or something else?

    string testData = @"<MSGIDRETURN>
                            <VERSION>1.0</VERSION>
                            <MSGID_LIST>
                                <MSGID>Test1234567</MSGID>
                            </MSGID_LIST>
                         </MSGIDRETURN>";
    
     XmlSerializer serializer = new XmlSerializer(typeof(MSGIDRETURN));
     StringReader rdr = new StringReader(testData.Trim());
     MSGIDRETURN resultingMessage = (MSGIDRETURN)serializer.Deserialize(rdr);