I'm having trouble serializing a list to XML, if the list is empty or null, I still want the element , unfortunately, I can't get this to work, the element is omitted.
public partial class Car {
string model;
string brand;
}
[XmlArray(IsNullable = true)]
[XMLArrayItem(Car)]
public list<Car> Cars
{
get { return _cars;
set { _cars = value;
}
I serialize in the following way
private string SerializeObject(object obj)
{
string res;
XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.DoNotEscapeUriAttributes = true;
writerSettings.Encoding = Encoding.UTF8;
writerSettings.CheckCharacters = true;
writerSettings.Indent = false;
writerSettings.NewLineHandling = NewLineHandling.None;
writerSettings.WriteEndDocumentOnClose = true;
writerSettings.OmitXmlDeclaration = true;
XmlWriterSettings xmlWriterSettings = writerSettings;
XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
StringWriter strWriter = new StringWriter();
XmlWriter xmlWriter = XmlWriter.Create(strWriter, xmlWriterSettings);
xmlSerializer.Serialize(xmlWriter, obj);
var doc = XElement.Parse(strWriter.ToString());
doc.Descendants().ToList().Where(d => d.Value.Length == 0 || d.Value == "0").Remove();
res = doc.ToString();
return res;
}
Any suggestions?