14

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.

4

3 回答 3

24

您可以控制必须序列化的项目吗?
使用

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

您可以将其表示为<Prop xsi:nil="true" />

于 2013-08-29T15:34:42.320 回答
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 回答
0

设置XmlElementAttribute.IsNullable属性:

https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlelementattribute.isnullable(v=vs.110).aspx

于 2013-08-29T15:35:12.960 回答