【问题标题】:XmlSerializer How to exclude null value but keep the tag ? c#XmlSerializer 如何排除空值但保留标签? C#
【发布时间】:2015-05-13 08:30:17
【问题描述】:

我的班级

    public MyClass
    {
       [DataMemberAttribute(EmitDefaultValue = true)]
       public decimal? a { get; set; }
       [DataMemberAttribute(EmitDefaultValue = true)]
       public DateTime? b { get; set; }
       [DataMemberAttribute(EmitDefaultValue = true)]
       public int? c { get; set; }
       [DataMemberAttribute(EmitDefaultValue = true)]
       public bool? d { get; set; }
    }

Decimal、DateTime 和 int 可以为空。所以我有:

<MyClass ...>
    <a>3</a>
    <b i:nil="true"/>
    <c i:nil="true"/>
    <d i:nil="true"/>
</MyClass>

当 a、b、c 为空时,我想得到这个:

<MyClass ...>
    <a>3</a>
    <b/>
    <c/>
    <d/>
</MyClass>

【问题讨论】:

    标签: c# asp.net xml-serialization nullable xmlserializer


    【解决方案1】:

    您只需要为您想要的每个元素创建如下属性:

     public MyClass
        {
    
        [System.Xml.Serialization.XmlElement("b",IsNullable = false)]
            public object b
            {
                get
                {
                    return b;
                }
                set
                {
                    if (value == null)
                    {
                        b = null;
                    }
                    else if (value is DateTime || value is DateTime?)
                    {
                        b = (DateTime)value;
                    }
                    else
                    {
                        b = DateTime.Parse(value.ToString());
                    }
                }
            }
    
     //public object b ....
    
    }
    

    【讨论】:

      【解决方案2】:

      我终于做到了:

      XmlSerializer.SerializeToWriter(data, strw);
      XDocument xdoc = XDocument.Load("myxmlfile.xml");
      
      foreach (var attribute in xdoc.Descendants())
      {
           if (attribute.FirstAttribute != null && attribute.FirstAttribute.ToString().Contains("i:nil"))
                  attribute.FirstAttribute.Remove();
      }
      xdoc.Save("myxmlfile.xml");
      

      在我的课上我有

      [DataMemberAttribute(EmitDefaultValue = true)]
      

      所以当它为 null 时,它会生成 'i:nil="true"',然后我只需要删除它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-09
        • 2015-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-15
        相关资源
        最近更新 更多