【问题标题】:Handle null while Serializing Class to xml in C#在 C# 中将类序列化为 xml 时处理 null
【发布时间】:2019-11-25 11:23:41
【问题描述】:

我正在尝试在 C# 中序列化一个类,当对象中没有空值时,它可以正常工作。以下是课程

public class EnquiryResponseInfo
{
    public string EnquiryId { get; set; }
    public EnquiryViewModel Enquiry { get; set; }
}

当我提供以下值时,效果很好。

EnquiryResponseInfo tt = new EnquiryResponseInfo()
{
    EnquiryId = "xxx",
    Enquiry = new EnquiryViewModel()
    {
        Name = "Test user",
        Address = "Test Address"
    }
}

但是当 Enquiry 为 null 时,它不会序列化。我有一个条件,即 Enquiry 将为空,但那里的 EnquiryId 会有值。

以下是序列化类的方法。

public static string Serialize<T>(T toSerialize)
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
    using (StringWriter textWriter = new StringWriter())
    {
        xmlSerializer.Serialize(textWriter, toSerialize);
        return textWriter.ToString();
    }
}

请帮忙。

【问题讨论】:

  • "但是当 Inquiry 为 null 时,它不会序列化。" - 查询不序列化?或者整个类型不序列化?如果属性为空,它应该可以正常工作 - 究竟会发生什么?显示它工作正常的示例,输出:gist.github.com/mgravell/bd817bebd0f4a3d52c5edf0bb4f0fcf8
  • List ApplicationInfo = new List() { new EnquiryResponseInfo() { EnquiryId = "e30a092d-b7c1-4516-8e48-50efe307c7e5", Inquiry = null } };
  • 反映类型“System.Collections.Generic.List`1[EnquiryResponseInfo]”时出现错误。给我这个错误...
  • “反映类型 'System.Collections.Generic.List`1[EnquiryResponseInfo]' 时出现错误” - 提示:查看 .InnerException - 和 .InnerException.InnerException 等(尽可能低)去); XmlSerializer 实际上非常擅长告诉你出了什么问题,但它通常是异常堆栈的几级
  • 这里有一个更新的要点,它使用您的 Serialize&lt;T&gt; 方法,并使用 List&lt;EnquiryResponseInfo&gt; 来匹配帖子/cmets:gist.github.com/mgravell/503a885c291a4eeee2be201473059f75 - 它工作正常 - 所以:无论问题是什么,它不在问题中;您需要发布足够的代码让我们重现问题,或者查看嵌套异常

标签: c# xml xml-serialization


【解决方案1】:

尝试用查询来装饰房产 [XmlElement(IsNullable = true)]

引自here

【讨论】:

  • 我现在发现,我认为这个值的使用是为了防止序列化器序列化该值,如果它为空,对吗? @MarcGravell
  • 不,不是;它已经这样做了 - 这只是导致它在为空时以特定方式被序列化,即在xml中表示为nil
【解决方案2】:

问题中的代码和cmetsis perfectly fineXmlSerializernull 有合理的默认行为,所以:这不是问题。

无论 is 发生了什么:问题中没有显示。 EnquiryViewModel 上的其他属性很可能对 XmlSerializer 不友好——它们可能是非公共类型,或者没有公共无参数构造函数。找出方法是查看嵌套异常——例如,在Serialize&lt;T&gt;

try
{
    // ... what you had before
}
catch (Exception ex)
{
    while (ex != null)
    {
        Debug.WriteLine(ex.Message);
        ex = ex.InnerException;
    }
    throw;
}

这应该告诉你它究竟在调试输出中发现模型对什么不满意(或者只是在Debug.WriteLine 行上放置一个断点,然后阅读调试器)。

【讨论】:

    【解决方案3】:

    将您的属性保持为可为空,这样可以解决问题。示例代码你可以参考下面。

     [XmlRoot("test")]  
        public class Test {  
            int? propertyInt;  
            string propertyString;  
    
            [XmlAttribute("property-int")]  
            public int PropertyInt {  
                get { return (int)propertyInt; }  
                set { propertyInt = (int)value; }  
            }  
    
            public bool PropertyIntSpecified {  
                get { return propertyInt != null; }  
            }  
    
            [XmlAttribute("property-string")]  
            public string PropertyString {  
                get { return propertyString; }  
                set { propertyString = value; }  
            }  
        }  
    
        class Program {  
            static void Main(string[] args) {  
    
                XmlSerializer serializer = new XmlSerializer(typeof(Test));  
                serializer.Serialize(Console.Out, new Test() { PropertyInt = 3 });  //only int will be serialized  
                serializer.Serialize(Console.Out, new Test() { PropertyString = "abc" }); // only string will be serialized  
                serializer.Serialize(Console.Out, new Test() { PropertyInt = 3, PropertyString = "abc" }); // both - int and string will be serialized  
    
    
            }  
        } 
    

    【讨论】:

      猜你喜欢
      • 2011-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多