XML Deserialize Missing Element
asp.net, c#, serialization, xml
Solution
You could do it with a backing field with a default value:
private string jobTitle = "";
[XmlElement("JobTitle")]
public string JobTitle { get {return jobTitle;} set {jobTitle = value;} }
or set it in the default constructor:
public PersonObject()
{
JobTitle = "";
NamePrefix = "";
FullName = "";
}
Problem
I'm deserialising some XML into my class, which is all working fine. What I want to happen is if the XML does not contain an element for one of my class properties, rather than set the property to null, I want to it to be the equivalent of String.Empty. For example, this is the XML: ``` <Person> <Title>Mr</Title> <FullName>John Smith</FullName> </Person> ``` This is the Class: ``` [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; } } ``` Currently if I deserialise into this object, JobTitle is set to null. I want this to be set to an empty string, much like it would be if I passed JobTitle in the XML, but had the value set to nothing. Is it possible to do this using some kind of property on the Serialisation method?