【问题标题】:How to include null properties during xml serialization如何在 xml 序列化期间包含空属性
【发布时间】:2016-10-14 21:13:41
【问题描述】:

目前,下面的代码在序列化过程中省略了空属性。我希望输出 xml 中的空值属性作为空元素。我搜索了网络,但没有找到任何有用的东西。任何帮助将不胜感激。

        var serializer = new XmlSerializer(application.GetType());
        var ms = new MemoryStream();
        var writer = new StreamWriter(ms);
        serializer.Serialize(writer, application);
        return ms;

对不起,我忘了说我要避免属性修饰。

【问题讨论】:

  • 为什么要这样做?这对我来说没有意义
  • 小心,空元素不等于不存在/空元素。例如,XML 序列化一个string 属性,一个空元素将为该属性生成一个空字符串"" (String.Empty),其中不存在的(或具有xsi:nil="true" 属性的元素)元素将生成同一属性的 null 参考值。

标签: c# xml serialization


【解决方案1】:

你能控制必须序列化的项目吗?
使用

[XmlElement(IsNullable = true)]
public string Prop { get; set; }

你可以表示为<Prop xsi:nil="true" />

【讨论】:

    【解决方案2】:

    您也可以使用以下代码。模式是ShouldSerialize{PropertyName}

    public class PersonWithNullProperties
    {
        public string Name { get; set; }
        public int? Age { get; set; }
        public bool ShouldSerializeAge()
        {
            return true;
        }
    }
    
      PersonWithNullProperties nullPerson = new PersonWithNullProperties() { Name = "ABCD" };
      XmlSerializer xs = new XmlSerializer(typeof(nullPerson));
      StringWriter sw = new StringWriter();
      xs.Serialize(sw, nullPerson);
    

    XML

    <?xml version="1.0" encoding="utf-16"?>
    <Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://
    www.w3.org/2001/XMLSchema">
      <Name>ABCD</Name>
      <Age xsi:nil="true" />
    </Person>
    

    【讨论】:

      【解决方案3】:
      猜你喜欢
      • 2011-01-28
      • 2019-01-26
      • 2019-06-08
      • 2016-05-26
      • 2013-08-17
      • 1970-01-01
      • 2010-11-18
      • 2023-03-12
      相关资源
      最近更新 更多