1

我想要一個類被序列化爲XML。 它的工作原理,但字符串屬性「origen」是全部序列化爲字符串,也是空的時候。 我想串行避免包括它的XML裏面當它是空XmlSerialization忽略字符串屬性如果爲空

類是FirmaElement,例如:

FirmaElement firma= new FirmaElement(); 
firma.Value="HITHERE"; 
firma.origen=String.Empty; 

預期的結果

string x= Serialize(FirmaElement); 
x="<Firma>HITHERE</Firma>"; 

FirmaElement firma= new FIrmaElement(); 
firma.Value="HITHERE"; 
firma.origen="OK"; 

預期成果

string x= Serialize(FirmaElement); 
x="<Firma origen='ok'>HITHERE</Firma>"; 

代碼

[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://gen/ces/headers/CesHeader")] 
[System.Xml.Serialization.XmlRoot("Firma")] 
public class FirmaElement 
{ 
    public FirmaElement() { } 
    string _origen = String.Empty; 
    string _value = String.Empty; 


    [System.Xml.Serialization.XmlAttributeAttribute()] 
    public string origen 
    { 
     get { return _origen; } 
     set { _origen = value; } 
    } 

    [System.Xml.Serialization.XmlTextAttribute()] 
    public string Value 
    { 
     get { return _value; } 
     set { _value = value; } 
    } 


    public override string ToString() 
    { 
     return this.Value; 
    } 


    //IS THIS CORRECT? SHould i override something?? 
    public string Serialize() 
    { 
     XmlAttributeOverrides xOver = new XmlAttributeOverrides(); 
     XmlAttributes attrs = new XmlAttributes(); 

     /* Setting XmlIgnore to false overrides the XmlIgnoreAttribute 
      applied to the Comment field. Thus it will be serialized.*/ 
     attrs.XmlIgnore = String.IsNullOrEmpty(origen); 
     xOver.Add(typeof(string), "origen", attrs); 

     I DONT KNOW WHAT TO PUT HERE, IT'S CORRECT?? 

     //XmlSerializer xSer = new XmlSerializer(typeof(XmlTypeAttribute), xOver); 
    } 



} 
+0

顯示沒有值的屬性origen有什麼危害? XML被設計爲處理數據格式,提供或不提供值。 –

+0

[Xml序列化 - 隱藏空值]的可能重複(http://stackoverflow.com/questions/5818513/xml-serialization-hide-null-values) –

回答

0

您可以指定特定的屬性是否應序列化或不與方法的幫助下與名ShouldSerialize{PropertyName}。檢查this answer了。

0

您應該將名爲origenSpecified的屬性添加到FirmaElement類中。

[XmlIgnore] 
    public bool origenSpecified 
    { 
     get 
     { 
      return !(string.IsNullOrEmpty(origen)); 
     } 
    }