Search code examples
c#xmlserializer

Deserialize alternative names for the same class


I have a serialier that is not totally unlike the following:

[Serializable]
public class MSG
{
    [XmlAttribute]
    public string Name { get; set; } = string.Empty;

    [XmlText]
    public string Content { get; set; } = string.Empty;
}

public MSG DeserializeMyMsg(string xmlstr)
{
    TextReader reader = new StringReader(xmlstr);
    var serializer = new XmlSerializer(typeof(MSG));
    MSG ret = serializer.Deserialize(reader) as MSG;
    return ret;
}

This would successfully deserialize the following:

<MSG Name="woho">any content</MSG>

Occasionally data can arrive as:

<Mg Name="woho">any content</Mg>

How can I mark Mg as an alternative name for MSG?


MSG is the root. Fixing Mg would be the long term goal but is not an option either. The messages could be retrofitted with an outer root.


Solution

  • You mentioned in a comment you could wrap your xml. This feels an awful lot like a hack but this works. Generally my advice would be don't do this!

    So your xml would be:

    <NewRoot><MSG Name="woho">any content</MSG></NewRoot>
    

    Or

    <NewRoot><Mg Name="woho">any content</Mg></NewRoot>
    

    Then define these classes and deserialize the above xml:

    public class NewRoot
    {
        [XmlElement("MSG", typeof(MSG))]
        [XmlElement("Mg", typeof(Mg))]
        public MSG Msg {get;set;}
    }
    
    public class Mg : MSG {}