XML Deserialize Missing Element

I am deserializing some XML into my class, which works fine. I want the XML to not contain an element for one of the properties of my class, and not set the null property, I want it to be the equivalent of String.Empty.

For example, this is 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 deserialize this object, the value of JobTitle is null. I want this to be set with an empty string, just as if I were passing the JobTitle to XML, but had a value meaning nothing.

Is it possible to do this using any property of the Serialization method?

+3
source share
1 answer

You can do this using the support field with the 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 = "";
}
+7
source

All Articles