I have a class containing an array I wish to serialize with XmlSerializer:
[XmlArray("properties")]
[XmlArrayItem("property", IsNullable = true)]
public List<Property> Properties { get; set; }
Property is a class containing an attribute and some XmlText:
[XmlAttribute("name")]
public string Name { get; set; }
[XmlText]
public string Value { get; set; }
The problem is that when Value is null, it serializes as an empty string:
<property name="foo" />
rather than a null. I’m looking for the value to either be omitted entirely, or look like this:
<property name="foo" xsi:nil="true" />
Is it possible to null out an element in a list based on its XmlText value? I’m really trying to avoid custom serialization, but perhaps some other serialization framework would be better in this case?
Use the IsNullable=true in the XmlArrayItemAttribute class. For an example.
Some sample code in Visual Studion 2012 and .Net 4.5:
The output is (line breaks added for clarity):
And with a complex type (also in .Net 4.5 on Visual Studio 2012):
Using the same code above produces:
Also remember that the type must be a reference type (not a struct, for example) to write out
xsi:nil=true.