How to include null properties during xml serializ

2020-07-03 06:40发布

Currently, the code below omits null properties during serialization. I want null valued properties in the output xml as empty elements. I searched the web but didn't find anything useful. Any help would be appreciated.

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

Sorry, I forgot to mention that I want to avoid attribute decoration.

3条回答
太酷不给撩
3楼-- · 2020-07-03 07:14

Can you control the items that have to be serialized?
Using

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

you can represent it as <Prop xsi:nil="true" />

查看更多
beautiful°
4楼-- · 2020-07-03 07:23

You can use also use the following code. The pattern is 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>
查看更多
登录 后发表回答