单个元素的Xml序列化覆盖

问题描述 投票:1回答:1

我有一个包含两个项目的对象列表。每个对象包含几个属性。我的问题是我必须将两个项目都序列化为xml,但是两个元素的属性都不同。

我已经尝试过XmlAttributeOverrides

示例类:

[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
    public class Apple
    {

[System.Xml.Serialization.XmlElementAttribute(DataType="nonNegativeInteger")]
       public int Index{ get; set;}

       [System.Xml.Serialization.XmlAttributeAttribute()]
       public int Size{ get; set;}

       [System.Xml.Serialization.XmlAttributeAttribute()]
       public decimal Weight{ get; set;}
    }

     void Test()
     {
        List<Apple> apples = new List<Apple>
        {
           new Apple {Index = 0, Size = 1},
           new Apple {Index = 1, Weight = 4}
        };
     }

序列化后的结果:

&ltApple Size = 1&gt&lt索引&gt0&lt /索引&gt&lt / Apple&gt&ltApple Weight = 4&gt&lt索引&gt1&lt /索引&gt&lt / Apple&gt
c# xml serialization overriding
1个回答
0
投票

这看起来像是“条件序列化”;在这里,我将Nullable<T>用作“此值是否有值?”的存储方式,public bool ShouldSerialize*()是许多序列化程序都可以识别的模式,它决定要做什么:

    private int? _size;
    [XmlAttribute]
    public int Size
    {
        get => _size.GetValueOrDefault();
        set => _size = value;
    }

    public bool ShouldSerializeSize() => _size.HasValue;

    private decimal? _weight;
    [XmlAttribute]
    public decimal Weight
    {
        get => _weight.GetValueOrDefault();
        set => _weight = value;
    }

    public bool ShouldSerializeWeight() => _weight.HasValue;

有了这个,序列化器基本上做(伪代码):

if (obj.ShouldSerializeSize()) output.WriteAttribute("Size", obj.Size);
if (obj.ShouldSerializeWeight()) output.WriteAttribute("Weight", obj.Weight);
© www.soinside.com 2019 - 2024. All rights reserved.