XmlSerializer和可空属性

问题描述 投票:28回答:2

我有一个具有许多Nullable <T>属性的类,我想将其作为属性序列化为XML。这显然是禁忌,因为它们被认为是“复杂类型”。所以,我实现了* Specified模式,我在其中创建了一个add * Value和* Specified属性,如下所示:

[XmlIgnore]
public int? Age
{
    get { return this.age; }
    set { this.age = value; }
}

[XmlAttribute("Age")]
public int AgeValue
{
    get { return this.age.Value; }
    set { this.age = value; }
}

[XmlIgnore]
public bool AgeValueSpecified
{
    get { return this.age.HasValue; }
}

哪个工作正常 - 如果'Age'属性有值,则将其序列化为属性。如果它没有值,则不会序列化。

问题在于,正如我所提到的,我的班级中有很多Nullable-s,这种模式只是让事情变得混乱和无法管理。

我希望有一种方法可以使Nullable更友好的XmlSerializer。或者,如果失败了,那就是创建Nullable替换的方法。

有没有人有任何想法我怎么能这样做?

谢谢。

c# .net attributes nullable xmlserializer
2个回答
10
投票

在你的课上实现IXmlSerializable界面。然后,您可以处理特殊情况,例如ReadXMLWriteXML方法中的nullables。 There's a good example in the MSDN documentation page.

 
class YourClass : IXmlSerializable
{
    public int? Age
    {
        get { return this.age; }
        set { this.age = value; }
    }

    //OTHER CLASS STUFF//

    #region IXmlSerializable members
    public void WriteXml (XmlWriter writer)
    {
        if( Age != null )
        {
            writer.WriteValue( Age )
        }
    }

    public void ReadXml (XmlReader reader)
    {
        Age = reader.ReadValue();
    }

    public XmlSchema GetSchema()
    {
        return(null);
    }
    #endregion
}

15
投票

我遇到了一些与我正在处理的代码类似的问题,我决定只使用字符串作为序列化和反序列化的属性。我最终得到了这样的东西:

[XmlAttribute("Age")]
public string Age
{
    get 
    { 
        if (this.age.HasValue)
            return this.age.Value.ToString(); 
        else
            return null;
    }
    set 
    { 
        if (value != null)
            this.age = int.Parse(value);
        else
            this.age = null;
    }
}

[XmlIgnore]
public int? age;
© www.soinside.com 2019 - 2024. All rights reserved.