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);
}
}
CodePudding user response:
Here is my suggestion: make multiple properties for deserializing, and create a main-property for further usage.
[Serializable]
public partial class Animal
{
public string Horse { get; set; }
public string Chicken { get; set; }
[XmlAttribute("blooded")]
public string BloodKind1 { get; set; }
[XmlAttribute("bloodtype")]
public string BloodKind2 { get; set; }
public string BloodKind
{
get
{
if(!string.IsNullOrEmpty(BloodKind1))
{
return BloodKind1;
}
// etcetera...
}
}
}
CodePudding user response:
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.