Search code examples
c#xmldeserialization

C# xml deserialization: InvalidOperationException (maybe namespace related?)


I receive from another piece of code a MemoryStream object that contains an xml document and I need to deserialize it:

XML:

<?xml version="1.0" encoding="utf-8"?>
<aaa:MyRootElement xmlns:aaa="http://www.example.com/config/1.0">
    <aaa:Configurations>
        <aaa:Configuration>
            <aaa:Field1>xxx</aaa:Field1>
            <aaa:Field2>abc</aaa:Field2>
        </aaa:Configuration>
    </aaa:Configurations>
</aaa:MyRootElement>

I wrote this code:

[XmlRoot("MyRootElement")]
public class ConfigInfo
{
    public class Configuration
    {
        public string Field1 { get; set; }
        public string Field2 { get; set; }
    }

    [XmlElement("Configurations")]
    public List<Configuration> Configurations { get; set; }

    public static ConfigInfo FromMemoryStream(MemoryStream memoryStream)
    {
        var r = new ConfigInfo();
        
        XmlSerializer serializer = new XmlSerializer(typeof(ConfigInfo));
        r = (ConfigInfo)serializer.Deserialize(memoryStream);   

        return r;
        
    }
}

Unfortunately it's giving me the following exception:

InvalidOperationException: <MyRootElement xmlns='http://www.example.com/config/1.0'> not expected.

I thing it has something to do with with the "aaa" namespace, but I have no clue on how to fix it.

Thank you


Solution

  • you missed Namespace attribute into your class. It should work now.

    [XmlRoot(ElementName = "MyRootElement", Namespace = "http://www.example.com/config/1.0")]
    public class ConfigInfo
    {
        [XmlElement("Configurations")]
        public List<Configuration> Configurations { get; set; }
    
        public static ConfigInfo FromMemoryStream(MemoryStream memoryStream)
        {
            var r = new ConfigInfo();
    
            XmlSerializer serializer = new XmlSerializer(typeof(ConfigInfo));
            r = (ConfigInfo)serializer.Deserialize(memoryStream);
    
            return r;
    
        }
    
        public class Configuration
        {
            public string Field1 { get; set; }
    
            public string Field2 { get; set; }
        }
    }