[英]Handle null while Serializing Class to xml in C#
我正在尝试在 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"
}
}
但是当Inquiry为空时,它不会序列化。 我有一个条件,其中Inquiry将为空,但那里的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();
}
}
请帮忙。
尝试用[XmlElement(IsNullable = true)]
装饰属性查询
从这里引用
问题和评论中显示的代码非常好; XmlSerializer
对null
具有合理的默认行为,因此:这不是问题。
无论是发生了什么:它不是在问题中。 最有可能的是, EnquiryViewModel
上还有其他对XmlSerializer
不友好的属性 - 也许它们是非公共类型,或者没有公共无参数构造函数。 找出的方法是查看嵌套异常- 例如,在Serialize<T>
:
try
{
// ... what you had before
}
catch (Exception ex)
{
while (ex != null)
{
Debug.WriteLine(ex.Message);
ex = ex.InnerException;
}
throw;
}
这应该会告诉您它在调试输出中究竟发现模型令人反感的地方(或者只是在Debug.WriteLine
行上放置一个断点,然后读取调试器中的所有消息)。
保持您的财产为可空,这将解决问题。 您可以在下面参考示例代码。
[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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.