0

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);
AsyncCoder
  • 11
  • 5
  • Possibly a duplicate of https://stackoverflow.com/q/17795167/22683 – Torbjörn Hansson Feb 28 '19 at 10:43
  • Just tried your solution, with string instead of input and it's working. What is your inputString? Is that file or something else? – zholinho Feb 28 '19 at 10:52
  • @zholinho thank you for answer. inputString has some invalid character like \" . now it is working. I edit my string as you write in testData and it will work. – AsyncCoder Feb 28 '19 at 11:18

1 Answers1

0

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);
zholinho
  • 460
  • 1
  • 5
  • 17