簡體   English   中英

如何在xml序列化期間包含null屬性

[英]How to include null properties during xml serialization

目前,以下代碼在序列化期間省略了null屬性。 我希望輸出xml中的null值屬性為空元素。 我在網上搜索但沒有找到任何有用的東西。 任何幫助,將不勝感激。

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

對不起,我忘了提到我想避免屬性修飾。

你能控制必須序列化的項目嗎?
運用

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

你可以把它表示為<Prop xsi:nil="true" />

您也可以使用以下代碼。 模式是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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM