无论出于何种原因,XmlSerializer 在序列化期间都不会包含空列表。我没有找到太多关于此行为是否正确或是否可以被覆盖的文档。我包括了我尝试序列化的类型的代码和序列化代码,希望有人能对此有所了解。
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://tempuri.org/FacilitySettings.xsd")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="http://tempuri.org/FacilitySettings.xsd", IsNullable=true)]
public class WeightSettings
{
public List<string> WeightOZIdentifiers
{
get
{
return this.weightOZIdentifiersField;
}
set
{
this.weightOZIdentifiersField = value;
}
}
}
public static string ToXmlString<T>(this T obj)
{
var builder = new StringBuilder();
using (var stringWriter = new StringWriter(builder))
{
var xml = new XmlTextWriter(stringWriter);
var serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(xml, obj);
return builder.ToString();
}
}
编辑以反射(reflect)
最佳答案
XmlSerializer
无法序列化一个空数组,因为他不知道这个数组的大小。
尝试先初始化数组,然后将其序列化。
WeightOZIdentifiers = new string[10];
关于c# - 如何强制 XmlSerializer 为空列表包含一个空标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18816357/