I'm writing a housekeeping application for a program I administer and I'm hitting a bit of a brick wall when trying to serialize a List
of custom classes to XML files.
I found this SO question that covered using an XMLSerializer
class to output Object data to XML. The key difference with what I'm trying to do is that I have a few different Lists containing unique data so I built a helper class with a generic static method to serialize/deserialize the data. The problem is that not all data is being serialized out so I can't deserialize it back into my application at a later date without encountering issues.
My method looks like this:
private static void SerializeObjectToXml<T>(List<T> inputList, string filePath)
{
XmlSerializer serializer = new XmlSerializer(typeof(List<T>));
using (FileStream stream = new FileStream(filePath, FileMode.Create))
{
serializer.Serialize(stream, inputList);
}
}
My data Object looks like this:
[XmlRoot("NameAddress")]
public class AppNameAddress
{
private string _OfficerCode;
private string _TelephoneNumber;
private string _EmailAddress;
public string OfficerCode { get { return _OfficerCode; } }
public string TelephoneNumber { get { return _TelephoneNumber; } }
public string EmailAddress { get { return _EmailAddress; } }
public string TeamName = "";
public bool IsOfficerManager = false;
public AppNameAddress() { }
public AppNameAddress(Dictionary<string, object> data)
{
_OfficerCode = data["OfficerCode"].ToString().Trim();
_TelephoneNumber = data["TelephoneNo1"].ToString().Trim();
_EmailAddress = data["EmailAddress"].ToString().Trim();
}
}
And my List declaration looks like this:
[XmlArray("NamesAddresses"), XmlArrayItem(typeof(AppNameAddress), ElementName = "NameAddress")]
public static List<AppNameAddress> NamesAddresses;
The problem is that the data being exported to the XML file looks like this:
<?xml version="1.0"?>
<ArrayOfAppNameAddress xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<AppNameAddress>
<TeamName />
<IsOfficerManager>false</IsOfficerManager>
</AppNameAddress>
<AppNameAddress>
<TeamName />
<IsOfficerManager>false</IsOfficerManager>
</AppNameAddress>
...
As you can see, the OfficerCode
, TelephoneNumber
and EmailAddress
parameters are not being exported. The only difference I can see is that there is no { set; }
for those variables as I want them to be read-only after initialising the Object but I can't see why that would affect the XmlSerializer
's ability to read the data and output it to XML. What am I doing wrong?