SORU
18 AĞUSTOS 2009, Salı


XmlSerializer tarafından Yayılan ve Null Değer Türleri bastırmak

Null bir XmlElement olarak işaretlenmiş: aşağıdaki Miktar türü özellik değeri düşünün lütfen

[XmlElement(IsNullable=true)] 
public double? Amount { get ; set ; }

Aşağıdaki gibi görünüyor XmlSerializer NULL değer türü null olarak ayarlandığında, C#:

<amount xsi:nil="true" />

Bu eleman yayan yerine, XmlSerializer öğe tamamen bastırmak istiyorum. Neden? Online ödeme için Authorize.NET kullanıyoruz ve Authorize.NET eğer bu boş bir öğe varsa, isteği reddeder.

Geçici çözüm/geçerli çözüm Miktarı türü özelliği hiç değeri seri hale getirmek için değil. Bunun yerine esas Tutar ve yerine sıralanmış olan tamamlayıcı özellik, SerializableAmount, yarattık. SerializableAmount tür referans türleri gibi XmlSerializer tarafından bastırılmış olan Dize, varsayılan olarak null olduğundan, her şey mükemmel çalışıyor.

/// <summary>
/// Gets or sets the amount.
/// </summary>
[XmlIgnore]
public double? Amount { get; set; }

/// <summary>
/// Gets or sets the amount for serialization purposes only.
/// This had to be done because setting value types to null 
/// does not prevent them from being included when a class 
/// is being serialized.  When a nullable value type is set 
/// to null, such as with the Amount property, the result 
/// looks like: >amount xsi:nil="true" /< which will 
/// cause the Authorize.NET to reject the request.  Strings 
/// when set to null will be removed as they are a 
/// reference type.
/// </summary>
[XmlElement("amount", IsNullable = false)]
public string SerializableAmount
{
    get { return this.Amount == null ? null : this.Amount.ToString(); }
    set { this.Amount = Convert.ToDouble(value); }
}

Tabii ki, bu sadece geçici bir çözüm. Temiz bir şekilde yayılan olmaktan null değer türü unsurları bastırmak için var mı?

CEVAP
18 AĞUSTOS 2009, Salı


Eklemeyi deneyin:

public bool ShouldSerializeAmount() {
   return Amount != null;
}

Desen çerçeve parçaları tarafından tanınan vardır. İçin bilgi, XmlSerializer public bool AmountSpecified {get;set;} arar.

Tam örnek (decimal geçiş):

using System;
using System.Xml.Serialization;

public class Data {
    public decimal? Amount { get; set; }
    public bool ShouldSerializeAmount() {
        return Amount != null;
    }
    static void Main() {
        Data d = new Data();
        XmlSerializer ser = new XmlSerializer(d.GetType());
        ser.Serialize(Console.Out, d);
        Console.WriteLine();
        Console.WriteLine();
        d.Amount = 123.45M;
        ser.Serialize(Console.Out, d);
    }
}

ShouldSerialize* on MSDN daha fazla bilgi.

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Dopelives

    Dopelives

    30 Temmuz 2009
  • efaustus9

    efaustus9

    16 HAZİRAN 2006
  • Rayone GB

    Rayone GB

    14 Temmuz 2007