Search code examples
c#xmlxml-parsingxmlserializerxml-deserialization

Issue with using XmlSerializer


Here is my C# code:

        public static T Deserialize<T>(string input) where T : class
        {
            System.Xml.Serialization.XmlSerializer ser = 
              new System.Xml.Serialization.XmlSerializer(typeof(T));

            using (StringReader sr = new StringReader(input))
            {
                var test = ser.Deserialize(sr); //*this is the line that breaks*
                return (T)ser.Deserialize(sr);
            }
        }

And here is my XML

<releaseinfo>
<mediapackagedirectory>C:\\Temp\\Test1\\</mediapackagedirectory>
<revision>A</revision>
<files>
    <file>C:\\Temp\\Test1\\test1.zip</file>
    <file>C:\\Temp\\Test1\\test1.zip</file>
</files>
<target>C:\\Temp\\Target\\</target>
</releaseinfo>

And here is the error I get:

Exception: {"There is an error in XML document (1, 2)."}
InnerException: {"<releaseinfo xmlns=''> was not expected."}

The error I am getting seems to have something to do with namespace even though my xml has no namespaces. It is exactly as is shown.


Solution

  • Assuming you've got some class "Releaseinfo", add the following attribute to the top:

    [Serializable, XmlRoot("releaseinfo")]
    public partial class Releaseinfo
    {
    ...
    }
    

    Here are more details:

    XmlRootAttribute Class

    ALSO:

    • Q: Why are you deserializing twice? Why not just return (T)ser.Deserialize(sr);? Was the first line just "test code"?

    • Just a side note: please try to use text (vs. screenshots) whenever possible.