14

現在、以下のコードはシリアル化中に null プロパティを省略しています。出力 xml の null 値のプロパティを空の要素として使用したい。Web を検索しましたが、有用なものは見つかりませんでした。どんな助けでも大歓迎です。

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

申し訳ありませんが、属性の装飾を避けたいということを忘れていました。

4

3 に答える 3

1

次のコードも使用できます。パターンは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>
于 2013-08-29T15:39:04.037 に答える