【问题标题】:XmlSerialization ignore string attribute if emptyXmlSerialization 如果为空则忽略字符串属性
【发布时间】:2017-08-08 18:25:53
【问题描述】:

我希望将一个类序列化为 XML。 它可以工作,但是字符串属性“origen”总是被序列化为 string ,当它为空时也是如此。 我希望序列化程序在它为 null 时避免将其包含在 XML 中

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



}

【问题讨论】:

标签: .net xml serialization xml-serialization xml-deserialization


【解决方案1】:

您应该在 FirmaElement 类中添加一个名为 origenSpecified 的属性。

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

【讨论】:

    【解决方案2】:

    您可以通过名称为ShouldSerialize{PropertyName} 的方法指定是否应序列化特定属性。签出this answer。

    【讨论】:

      猜你喜欢
      • 2018-10-12
      • 1970-01-01
      • 2011-10-18
      • 1970-01-01
      • 2021-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多