I am facing some errors while de-serializing an xml response into objects.Trying to get some data from an external API which returns xml response and convert to object. Error: was not expected, my xml below:
<markets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://test.sample.org/schemas/markets.xsd">
<Fund>
<values>
<Date>2020-11-23</Date>
<Number>xxxxxxx</Number>
<Description>test1</Description>
<Duration>30</Duration>
<currentValue>1000000</currentValue>
<isExist>"Y"</isExist>
<Type>Data</Type>
</values>
<values>
<Date>2020-11-23</Date>
<Number>xxxxxxx</Number>
<Description>test2</Description>
<Duration>31</Duration>
<currentValue>20000000</currentValue>
<isExist>"Y"</isExist>
<Type>Data</Type>
</values>
</Fund>
</markets>
Below is my class containing all the xml roots and elements that I tried to construct to form an object class.
[Serializable]
[XmlRoot(ElementName = "markets", Namespace = "http://test.sample.org/schemas/markets.xsd", IsNullable = false)]
public class Markets
{
[XmlElement(ElementName = "Fund")]
public Fund Fund { get; set; }
}
[XmlRoot("Fund")]
public class Fund
{
[XmlElement(ElementName = "values")]
public List<Values> values = new List<Values>();
}
[XmlRoot("values")]
public class Values
{
[XmlElement("Date")]
public DateTime AsOfDate { get; set; }
[XmlElement("Number")]
public string Number{ get; set; }
[XmlElement("Description")]
public string Descr { get; set; }
[XmlElement("Duration")]
public string Duration { get; set; }
[XmlElement("currentValue")]
public decimal CurrValue { get; set; }
[XmlElement("isExist")]
public string IsExist { get; set; }
[XmlElement("Type")]
public string Type { get; set; }
}
What am I doing wrong here? My xml can't be changed. Please suggest, you help is appreciated.
My De-serializer code:
using (var httpClient = new HttpClient())
{
try
{
HttpResponseMessage response = httpClient.GetAsync(apiurl).Result;
if (response.IsSuccessStatusCode)
{
new WebClient().DownloadFile(apiurl, fullPathName);//downloading the xml file to a physical location
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
string xml = File.ReadAllText(fullPathName);
XmlSerializer serializer = new XmlSerializer(typeof(Markets));
StringReader rdr = new StringReader(xml);
var resultingMessage = (Markets)serializer.Deserialize(rdr); //here I get all the objects