Search code examples
c#xmlserializationdatacontract

Trouble deserialising xml file using DataContractSerializer


It's been awhile since i've used DataContractSerializer and i'm having a little trouble deserializing a xml file.

<?xml version="1.0" encoding="utf-8"?> <SoftwareLicense xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

The error i'm getting is:

{"Error in line 1 position 117. Expecting element 'SoftwareLicense' from namespace 'http://schemas.datacontract.org/2004/07/Solentim.Modules.Licensing.Activation'.. Encountered 'Element' with name 'SoftwareLicense', namespace ''. "}

[DataContract(Name = "SoftwareLicense")]
public class SoftwareLicense : ISoftwareLicense
{
    ...
}

I've tried specifying the namespace which also doesn't work.

var serializer = new DataContractSerializer(typeof(SoftwareLicense));

using (var stream = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
    using (var reader =
                XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas()))
    {
        return (SoftwareLicense) serializer.ReadObject(reader);
    }
}

The namespace of the file has recently changed and an interface added to the class. I've resolved all other issues i just can't seem to get around this one.

I prefer to use the DatacontractSerializer as the class now has interface properties and XMLSerializer won't deserialise it


Solution

  • This answer may help you to solve your problem.

    If you prefer to use XmlSerializer. Here is the simple implementation below:

    private T Deserialize<T>(string path) where T : class
    {
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        T result = null;
        using (XmlReader reader = XmlReader.Create(path))
        {
           result = (T)serializer.Deserialize(reader);
        }
        return result;
    }