Deserializing XML with namespace and multiple nested elements

The problem is that the namespace of myrootNS class is incorrect because it doesn't match the expected namespace in the XML.

[XmlRoot("myroot", Namespace = "http://jeson.com/")]
public class myrootNS
{
    [XmlElement(Namespace = "")]
    public item[] item { get; set; }
}

Notice that the Namespace property value has a trailing /. This is my deserialize method:

static T Deserialize<T>(string xml)
{
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    XmlReaderSettings settings = new XmlReaderSettings();
    using (StringReader textReader = new StringReader(xml))
    {
        using (XmlReader xmlReader = XmlReader.Create(textReader, settings))
        {
            return (T)serializer.Deserialize(xmlReader);
        }
    }
}

As an alternative to the XmlRoot attribute, you can also use the alternative XmlRootAttribute constructor of XmlSerializer to override when the element name or namespace differ:

var serializer = new XmlSerializer(typeof(myrootNS), 
                     new XmlRootAttribute                             
                     { 
                         ElementName = "myroot", 
                         Namespace = "http://jeson.com/" 
                     });

Tags:

C#

Xml