在C#中将类序列化为xml时处理null

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
EnquiryResponseInfo tt = new EnquiryResponseInfo()
{
    EnquiryId ="xxx",
    Enquiry = new EnquiryViewModel()
    {
        Name ="Test user",
        Address ="Test Address"
    }
}

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

以下是序列化类的方法。

1
2
3
4
5
6
7
8
9
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)]

从这里引用


问题和注释中显示的代码非常正确; XmlSerializernull具有合理的默认行为,因此:这不是问题。

无论发生什么事:问题中都没有显示。 EnquiryViewModel上很可能存在其他对XmlSerializer不友好的属性-也许它们是非公共类型,或者没有公共无参数构造函数。查找的方法是查看嵌套的异常-例如,在Serialize<T>

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;
}

这应该告诉您在调试输出中(或者只是在Debug.WriteLine行上放置一个断点,并读取调试器中的所有消息)它真正对模型有什么异议。


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

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  


        }  
    }