I've looked through the various questions on here similar to this, but can't get my solution to work.
I'm using Visual Studio 2015 Community, building a WPF project.
I get xml from my backend API, and I'm trying to convert it into a C# object, but I can't get it to work.
This is the xml
<response>
<computer_setting id="1" hospital_name="foo" computer_type="bar" environment="staging" label_printer_name="labels" document_printer_name="docs"/>
</response>
This is class
using System.Xml.Serialization;
namespace Casechek.Kiosk
{
[XmlRoot("response")]
public class ComputerSettingResponse
{
[XmlElement("computer_setting")]
internal ComputerSetting Settings { get; set; }
}
internal class ComputerSetting
{
[XmlAttribute("id")]
internal string Id { get; set; }
[XmlAttribute("hospital_name")]
internal string HospitalName { get; set; }
[XmlAttribute("computer_type")]
internal string ComputerType { get; set; }
[XmlAttribute("environment")]
internal string Environment { get; set; }
[XmlAttribute("label_printer_name")]
internal string LabelPrinterName { get; set; }
[XmlAttribute("document_printer_name")]
internal string DocumentPrinterName { get; set; }
}
}
And this is my attempt to deserialize it
// Get ComputerSettings
String _Url = this.ApiUrl
+ "/api1/hospitals/foo/settings.xml"
+ "?access_token=" + Authentication.AccessToken;
XmlSerializer _Serializer = new XmlSerializer(typeof(ComputerSettingResponse));
ComputerSettingResponse _ComputerSettingResponse = new ComputerSettingResponse();
using (XmlTextReader _XmlReader = new XmlTextReader(_Url))
{
_ComputerSettingResponse = (ComputerSettingResponse)_Serializer.Deserialize(_XmlReader);
Debug.WriteLine(_ComputerSettingResponse.Settings.Environment);
}
But this throws NullReference exception when it gets to Debug.WriteLine()
{"Object reference not set to an instance of an object."}
I've checked that the url is returning the xml properly, so it must me a poorly constructed class, or I'm not doing the deserialization properly.