我是将一些XML序列化到我的类中,这很正常。但是如果XML不包含我类的某个属性元素时,我希望它的值为String.Empty而不是null。例如,以下是XML:
这是一个类:
<Person>
<Title>Mr</Title>
<FullName>John Smith</FullName>
</Person>
这是一个类:
[XmlRoot("Person")]
public sealed class PersonObject
{
[XmlElement("Title")]
public string NamePrefix { get; set; }
[XmlElement("FullName")]
public string FullName { get; set; }
[XmlElement("JobTitle")]
public string JobTitle { get; set; }
}
目前,如果我将数据反序列化到这个对象中,JobTitle字段被设置为null。我希望它被设置为空字符串,就像在XML中传递JobTitle但没有设置值一样。
是否可能通过序列化方法的某种属性来实现?
XmlElementAttribute
的自定义属性来实现这一点。不过我必须问一下,为什么null
很重要呢?您不能在代码中处理它吗? - Yuck