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)); 
     } 
    }