简体   繁体   English

如何将 map 多个 xml 属性转换为单个 c# 属性进行反序列化?

[英]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] .我不能使用[XmlChoiceIdentifier] ,因为与[XmlElement]不同,不允许使用多个[XmlAttribute] ]。 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.这将导致文件膨胀和许多 null 检查。 Can't change the xml I'm working with.无法更改我正在使用的 xml。 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);
    }

}

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.基本上,我们已经使Blooded成为BloodKind的直通代理,并且只有BloodKind被考虑用于序列化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM