Search code examples
c#xmlattributesdeserializationlinq-to-xml

How do I map multiple xml attributes to a single c# property on deserialization?


I can't use the [XmlChoiceIdentifier] because multiple[XmlAttribute] isn't allowed unlike [XmlElement]. The standard solution to create multiple properties for each attribute name is unwieldy in my situation. It will result in a bloated file and many null checks. Can't change the xml I'm working with. Small example of my issue below.

<Animal blooded="warm"> <!--The attribute can be "blooded", "bloodtype", etc.-->
    <Horse>Jack</Horse>
    <Chicken>Charlie</Chicken>
</Animal>
[Serializable]
public partial class Animal
{
    public string Horse { get; set; }

    public string Chicken { get; set; }

    [XmlAttribute("blooded")]
    public string BloodKind { get; set; }
}

I want to write

    [XmlAttribute("blooded")]
    [XmlAttribute("bloodtype")] // <------ trying to do this, any work around?
    public string BloodKind { get; set; }
public class Program
{
    public static void Main( string[] args )
    {
        XmlSerializer serializer = new XmlSerializer( typeof(Animal) );
        using Stream reader = new FileStream( "data.xml", FileMode.Open );
        Animal animal = (Animal)serializer.Deserialize(reader);

        Console.WriteLine(animal.BloodKind);
    }

}

Solution

  • Perhaps:

    [XmlAttribute("blooded")]
    public string Blooded
    {
        get => BloodKind;
        set => BloodKind = value;
    }
    public bool ShouldSerializeBlooded() => false;
    
    [XmlAttribute("bloodtype")]
    public string BloodKind { get; set; }
    

    Basically, we've made Blooded a pass-thru proxy to BloodKind, and only BloodKind is considered for serialization.