【问题标题】:How to force XmlSerializer to include an empty tag for empty list如何强制 XmlSerializer 为空列表包含一个空标记
【发布时间】:2013-09-15 19:06:17
【问题描述】:

无论出于何种原因,在序列化过程中 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();
     }
}

编辑反映

【问题讨论】:

    标签: c# .net xml


    【解决方案1】:

    XmlSerializer 不能序列化一个空数组,因为他不知道这个数组的大小。 尝试先初始化数组,再序列化。

    WeightOZIdentifiers = new string[10];
    

    【讨论】:

    • Jacob,我的对象模型实际上使用的是列表而不是数组。编辑问题以反映这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-06
    • 1970-01-01
    相关资源
    最近更新 更多