Handle null while Serializing Class to xml in C#
我试图在C#中序列化一个类,当对象中没有空值时,此方法工作正常。以下是类
1 2 3 4 5 | public class EnquiryResponseInfo { public string EnquiryId { get; set; } public EnquiryViewModel Enquiry { get; set; } } |
当我提供以下值时,效果很好。
1 2 3 4 5 6 7 8 9 |
但是当Inquiry为null时,它不会序列化。我有一个条件,其中Inquiry将为null,但那里的EnquiryId中将有值。
以下是序列化类的方法。
1 2 3 4 5 6 7 8 9 |
请帮助。
尝试用来装饰房产
从这里引用
问题和注释中显示的代码非常正确;
无论发生什么事:问题中都没有显示。
中
1 2 3 4 5 6 7 8 9 10 11 12 13 | try { // ... what you had before } catch (Exception ex) { while (ex != null) { Debug.WriteLine(ex.Message); ex = ex.InnerException; } throw; } |
这应该告诉您在调试输出中(或者只是在
将您的属性保留为可为空,这将解决问题。您可以在下面参考示例代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | [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 } } |