I am trying to deserialize some XML returned in an API response but all the values in my object are NULL after deserializing.
Below is the XML I am getting in the response that I am trying to deserialize.
<?xml version="1.0" encoding="utf-8"?>
<ctatt>
<tmst>20160609 11:50:03</tmst>
<errCd>0</errCd>
<errNm />
<eta>
<staId>41300</staId>
<stpId>30252</stpId>
<staNm>Loyola</staNm>
<stpDe>Service toward 95th/Dan Ryan</stpDe>
<rn>803</rn>
<rt>Red</rt>
<destSt>30089</destSt>
<destNm>95th/Dan Ryan</destNm>
<trDr>5</trDr>
<prdt>20160609 11:48:45</prdt>
<arrT>20160609 11:51:45</arrT>
<isApp>0</isApp>
<isSch>0</isSch>
<isDly>0</isDly>
<isFlt>0</isFlt>
<flags />
<lat>42.01906</lat>
<lon>-87.67289</lon>
<heading>130</heading>
</eta>
</ctatt>
Here is my class:
[Serializable, XmlRoot("ctatt")]
public class trainData
{
[XmlElement(ElementName ="tmst")]
public string timeStamp { get; set; }
[XmlElement(ElementName = "errCd")]
public byte errorCode { get; set; }
[XmlElement(ElementName = "staId")]
public ushort stationId { get; set; }
[XmlElement(ElementName = "stpId")]
public ushort stopId { get; set; }
[XmlElement(ElementName = "staNm")]
public string stationName { get; set; }
[XmlElement(ElementName = "stpDe")]
public string stopDesc { get; set; }
[XmlElement(ElementName = "rn")]
public ushort runNum { get; set; }
[XmlElement(ElementName = "rt")]
public string routeName { get; set; }
[XmlElement(ElementName = "destSt")]
public ushort destStation { get; set; }
[XmlElement(ElementName = "destNm")]
public string destName { get; set; }
[XmlElement(ElementName = "trDr")]
public byte trainDir { get; set; }
[XmlElement(ElementName = "prdt")]
public string prdTime {get; set;}
[XmlElement(ElementName = "arrT")]
public string arrTime { get; set; }
[XmlElement(ElementName = "isApp")]
public ushort isApp { get; set; }
[XmlElement(ElementName = "isSch")]
public ushort isSch { get; set; }
[XmlElement(ElementName = "isDly")]
public ushort isDly { get; set; }
[XmlElement(ElementName = "isFlt")]
public ushort isFlt { get; set; }
[XmlElement(ElementName = "flags")]
public string flags { get; set; }
[XmlElement(ElementName = "lat")]
public double lat { get; set; }
[XmlElement(ElementName = "lon")]
public double lon { get; set; }
[XmlElement(ElementName = "heading")]
public ushort heading { get; set; }
}
And here is the code I am using to deserialize:
var response = await client.GetAsync(urlParameters);
if (response.IsSuccessStatusCode)
{
var xml = await response.Content.ReadAsStringAsync();
XmlSerializer deserializer = new XmlSerializer(typeof(trainData));
using (StringReader reader = new StringReader(xml))
{
using (XmlReader xr = XmlReader.Create(reader))
{
trainData result = (trainData)deserializer.Deserialize(xr);
Console.WriteLine("Station Name: {0}\nRoute Name: {1}\nArrival Time: {2}", result.stationName, result.routeName, result.arrTime);
}
}
}
else
{
Console.WriteLine("There was an error!");
}
Any suggestions would be greatly appreciated...
The xml you provided has 2 layers ctatt and eta. Yet your model has only a single layer. Of course this is not going to work.
You need to change your model to keep the layout the same with the xml :
[Serializable, XmlRoot("ctatt")]
public class trainDataResult
{
[XmlElement(ElementName ="tmst")]
public string timeStamp { get; set; }
[XmlElement(ElementName = "errCd")]
public byte errorCode { get; set; }
// uncomment next lines to include `errNm`
//[XmlElement(ElementName = "errNm")]
//public string errorName { get; set; }
[XmlElement(ElementName = "eta")]
public TrainData eta { get; set; }
}
public class TrainData
{
[XmlElement(ElementName = "staId")]
public ushort stationId { get; set; }
[XmlElement(ElementName = "stpId")]
public ushort stopId { get; set; }
[XmlElement(ElementName = "staNm")]
public string stationName { get; set; }
[XmlElement(ElementName = "stpDe")]
public string stopDesc { get; set; }
[XmlElement(ElementName = "rn")]
public ushort runNum { get; set; }
[XmlElement(ElementName = "rt")]
public string routeName { get; set; }
[XmlElement(ElementName = "destSt")]
public ushort destStation { get; set; }
[XmlElement(ElementName = "destNm")]
public string destName { get; set; }
[XmlElement(ElementName = "trDr")]
public byte trainDir { get; set; }
[XmlElement(ElementName = "prdt")]
public string prdTime {get; set;}
[XmlElement(ElementName = "arrT")]
public string arrTime { get; set; }
[XmlElement(ElementName = "isApp")]
public ushort isApp { get; set; }
[XmlElement(ElementName = "isSch")]
public ushort isSch { get; set; }
[XmlElement(ElementName = "isDly")]
public ushort isDly { get; set; }
[XmlElement(ElementName = "isFlt")]
public ushort isFlt { get; set; }
[XmlElement(ElementName = "flags")]
public string flags { get; set; }
[XmlElement(ElementName = "lat")]
public double lat { get; set; }
[XmlElement(ElementName = "lon")]
public double lon { get; set; }
[XmlElement(ElementName = "heading")]
public ushort heading { get; set; }
}
I only know how to deserialize a list of elements from a file but maybe it helps...
List<trainData> result = new List<trainData>;
using (FileStream stream = new FileStream(Filepath,Filemode.Open)
{
XmlSerializer Serializer =new XmlSerializer(typeof(List<trainData>));
result = Serializer.Deserialize(stream);
}
If is a complexType, I believe it need as class to represent that entire element. Create a second class (for example "ETAData") to contain the elements under the . You will also need a property of that type in your trainData class and have it marked with [XmlElementAttribute] also.
EDIT: #Xiaoy312 answer is more concise and basically illustrates what I stated.
Related
I am working on a project that calls an API (using C# ASP.NET), and the API returns an XML document. I know how to deserialize an response in JSON, but am running into issues with deserializing an XML response. Currently I am getting the below error when attempting to deserialize the XML:
InvalidOperationException: response xmlns="" was not expected.
The error code displayed just the empty quotes in the error message. I have the code samples below, and I would greatly appreciate any constructive feedback or advice on making this better, and any advice on where I went wrong on attempting to deserialize this!
Here is the XML response from the API call (This API only returns either CML or a .csv):
<response xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:noNamespaceSchemaLocation="http://www.aviationweather.gov/static/adds/schema/metar1_2.xsd">
<request_index>554967903</request_index>
<data_source name="metars"/>
<request type="retrieve"/>
<errors/>
<warnings/>
<time_taken_ms>7</time_taken_ms>
<data num_results="3">
<METAR>
<raw_text>KDEN 102353Z 15007KT 10SM FEW220 07/M08 A3038 RMK AO2 SLP285 T00721083 10133 20072 58015</raw_text>
<station_id>KDEN</station_id>
<observation_time>2022-01-10T23:53:00Z</observation_time>
<latitude>39.85</latitude>
<longitude>-104.65</longitude>
<temp_c>7.2</temp_c>
<dewpoint_c>-8.3</dewpoint_c>
<wind_dir_degrees>150</wind_dir_degrees>
<wind_speed_kt>7</wind_speed_kt>
<visibility_statute_mi>10.0</visibility_statute_mi>
<altim_in_hg>30.380905</altim_in_hg>
<sea_level_pressure_mb>1028.5</sea_level_pressure_mb>
<quality_control_flags>
<auto_station>TRUE</auto_station>
</quality_control_flags>
<sky_condition sky_cover="FEW" cloud_base_ft_agl="22000"/>
<flight_category>VFR</flight_category>
<three_hr_pressure_tendency_mb>-1.5</three_hr_pressure_tendency_mb>
<maxT_c>13.3</maxT_c>
<minT_c>7.2</minT_c>
<metar_type>METAR</metar_type>
<elevation_m>1656.0</elevation_m>
</METAR>
<METAR>
<raw_text>KSEA 102353Z 34003KT 6SM -RA BR FEW015 BKN035 OVC045 08/06 A3035 RMK AO2 SLP288 P0000 60001 T00780056 10083 20044 50003</raw_text>
<station_id>KSEA</station_id>
<observation_time>2022-01-10T23:53:00Z</observation_time>
<latitude>47.45</latitude>
<longitude>-122.32</longitude>
<temp_c>7.8</temp_c>
<dewpoint_c>5.6</dewpoint_c>
<wind_dir_degrees>340</wind_dir_degrees>
<wind_speed_kt>3</wind_speed_kt>
<visibility_statute_mi>6.0</visibility_statute_mi>
<altim_in_hg>30.351377</altim_in_hg>
<sea_level_pressure_mb>1028.8</sea_level_pressure_mb>
<quality_control_flags>
<auto_station>TRUE</auto_station>
</quality_control_flags>
<wx_string>-RA BR</wx_string>
<sky_condition sky_cover="FEW" cloud_base_ft_agl="1500"/>
<sky_condition sky_cover="BKN" cloud_base_ft_agl="3500"/>
<sky_condition sky_cover="OVC" cloud_base_ft_agl="4500"/>
<flight_category>VFR</flight_category>
<three_hr_pressure_tendency_mb>0.3</three_hr_pressure_tendency_mb>
<maxT_c>8.3</maxT_c>
<minT_c>4.4</minT_c>
<precip_in>0.005</precip_in>
<pcp6hr_in>0.01</pcp6hr_in>
<metar_type>METAR</metar_type>
<elevation_m>115.0</elevation_m>
</METAR>
<METAR>
<raw_text>PHNL 102353Z 19009KT 10SM FEW025 FEW035 SCT050 26/21 A2997 RMK AO2 SLP147 T02560206 10261 20200 58017</raw_text>
<station_id>PHNL</station_id>
<observation_time>2022-01-10T23:53:00Z</observation_time>
<latitude>21.33</latitude>
<longitude>-157.93</longitude>
<temp_c>25.6</temp_c>
<dewpoint_c>20.6</dewpoint_c>
<wind_dir_degrees>190</wind_dir_degrees>
<wind_speed_kt>9</wind_speed_kt>
<visibility_statute_mi>10.0</visibility_statute_mi>
<altim_in_hg>29.970472</altim_in_hg>
<sea_level_pressure_mb>1014.7</sea_level_pressure_mb>
<quality_control_flags>
<auto_station>TRUE</auto_station>
</quality_control_flags>
<sky_condition sky_cover="FEW" cloud_base_ft_agl="2500"/>
<sky_condition sky_cover="FEW" cloud_base_ft_agl="3500"/>
<sky_condition sky_cover="SCT" cloud_base_ft_agl="5000"/>
<flight_category>VFR</flight_category>
<three_hr_pressure_tendency_mb>-1.7</three_hr_pressure_tendency_mb>
<maxT_c>26.1</maxT_c>
<minT_c>20.0</minT_c>
<metar_type>METAR</metar_type>
<elevation_m>2.0</elevation_m>
</METAR>
</data>
</response>
This is the code to call the API:
private static readonly HttpClient client = new HttpClient();
static async Task Main(string[] args)
{
client.DefaultRequestHeaders.Accept.Clear();
string baseUrl = "https://www.aviationweather.gov/adds/dataserver_current/httpparam?dataSource=metars&requestType=retrieve&format=xml&stationString=KMSP&hoursBeforeNow=2";
client.BaseAddress = new Uri(baseUrl);
HttpResponseMessage result = client.GetAsync(baseUrl).Result;
XmlSerializer serialObject = new XmlSerializer(typeof(MetarReport));
List<MetarReport> MetarCollection = new List<MetarReport>();
if (result.IsSuccessStatusCode)
{
using (Stream reader = result.Content.ReadAsStreamAsync().Result)
{
MetarReport metar = new MetarReport();
metar = (MetarReport)serialObject.Deserialize(reader);
MetarCollection.Add(metar);
}
}
// Test deserializer
foreach(var item in MetarCollection)
{
Console.WriteLine(item.rawText);
}
Console.ReadLine();
}
And this is the object I am attempting to deserialize the XML into
[XmlRoot("METAR")]
[XmlType("METAR")]
public class MetarReport
{
[XmlElement("raw_text")]
public string rawText { get; set; }
[XmlElement("station_id")]
public string stationId { get; set; }
[XmlElement("latitude")]
public double latitiude { get; set; }
[XmlElement("longitude")]
public double longitude { get; set; }
[XmlElement("temp_c")]
public double tempCelsius { get; set; }
[XmlElement("dewpoint_c")]
public double dewpoint { get; set; }
[XmlElement("wind_dir_degree")]
public int windDirection { get; set; }
[XmlElement("wind_speed_kt")]
public double windspeed { get; set; }
[XmlElement("visibility_statute_mi")]
public double visbilityMiles { get; set; }
[XmlElement("altim_in_hg")]
public double altimeter { get; set; }
//[XmlElement("sky_condition")]
//public List<SkyCondition> skyConditions {get; set;}
[XmlElement("flight_category")]
public string flightCategory { get; set; }
[XmlElement("metar_type")]
public string metarType { get; set; }
[XmlElement("elevation_m")]
public double elevationMeters { get; set; }
}
try this, it was tested in Visual Studio
HttpResponseMessage response= client.GetAsync(baseUrl).Result;
string xml;
if (response.IsSuccessStatusCode)
{
xml = response.Content.ReadAsStringAsync().Result;
}
Response result;
XmlSerializer serializer = new XmlSerializer(typeof(Response));
using (StringReader reader = new StringReader(xml))
{
result = (Response)serializer.Deserialize(reader);
}
classes
[XmlRoot(ElementName = "response")]
public class Response
{
[XmlElement(ElementName = "request_index")]
public int RequestIndex { get; set; }
[XmlElement(ElementName = "data_source")]
public DataSource DataSource { get; set; }
[XmlElement(ElementName = "request")]
public Request Request { get; set; }
[XmlElement(ElementName = "errors")]
public object Errors { get; set; }
[XmlElement(ElementName = "warnings")]
public object Warnings { get; set; }
[XmlElement(ElementName = "time_taken_ms")]
public int TimeTakenMs { get; set; }
[XmlElement(ElementName = "data")]
public Data Data { get; set; }
[XmlAttribute(AttributeName = "xsd")]
public string Xsd { get; set; }
[XmlAttribute(AttributeName = "xsi")]
public string Xsi { get; set; }
[XmlAttribute(AttributeName = "version")]
public string Version { get; set; }
[XmlAttribute(AttributeName = "noNamespaceSchemaLocation")]
public string NoNamespaceSchemaLocation { get; set; }
[XmlText]
public string Text { get; set; }
}
[XmlRoot(ElementName = "quality_control_flags")]
public class QualityControlFlags
{
[XmlElement(ElementName = "auto_station")]
public string AutoStation { get; set; }
}
[XmlRoot(ElementName = "sky_condition")]
public class SkyCondition
{
[XmlAttribute(AttributeName = "sky_cover")]
public string SkyCover { get; set; }
[XmlAttribute(AttributeName = "cloud_base_ft_agl")]
public int CloudBaseFtAgl { get; set; }
}
[XmlRoot(ElementName = "METAR")]
public class METAR
{
[XmlElement(ElementName = "sky_condition")]
public List<SkyCondition> SkyCondition { get; set; }
[XmlElement(ElementName = "flight_category")]
public string FlightCategory { get; set; }
[XmlElement(ElementName = "three_hr_pressure_tendency_mb")]
public double ThreeHrPressureTendencyMb { get; set; }
[XmlElement(ElementName = "maxT_c")]
public decimal MaxTC { get; set; }
[XmlElement(ElementName = "minT_c")]
public decimal MinTC { get; set; }
[XmlElement(ElementName = "precip_in")]
public double PrecipIn { get; set; }
[XmlElement(ElementName = "pcp6hr_in")]
public double Pcp6hrIn { get; set; }
[XmlElement(ElementName = "metar_type")]
public string MetarType { get; set; }
[XmlElement(ElementName = "elevation_m")]
public double ElevationM { get; set; }
[XmlElement(ElementName = "raw_text")]
public string RawText { get; set; }
[XmlElement(ElementName = "station_id")]
public string StationId { get; set; }
[XmlElement(ElementName = "observation_time")]
public DateTime ObservationTime { get; set; }
[XmlElement(ElementName = "latitude")]
public double Latitude { get; set; }
[XmlElement(ElementName = "longitude")]
public double Longitude { get; set; }
[XmlElement(ElementName = "temp_c")]
public double TempC { get; set; }
[XmlElement(ElementName = "dewpoint_c")]
public double DewpointC { get; set; }
[XmlElement(ElementName = "wind_dir_degrees")]
public int WindDirDegrees { get; set; }
[XmlElement(ElementName = "wind_speed_kt")]
public int WindSpeedKt { get; set; }
[XmlElement(ElementName = "visibility_statute_mi")]
public double VisibilityStatuteMi { get; set; }
[XmlElement(ElementName = "altim_in_hg")]
public double AltimInHg { get; set; }
[XmlElement(ElementName = "sea_level_pressure_mb")]
public decimal SeaLevelPressureMb { get; set; }
[XmlElement(ElementName = "quality_control_flags")]
public QualityControlFlags QualityControlFlags { get; set; }
}
[XmlRoot(ElementName = "data")]
public class Data
{
[XmlElement(ElementName = "METAR")]
public List<METAR> METAR { get; set; }
[XmlAttribute(AttributeName = "num_results")]
public int NumResults { get; set; }
[XmlText]
public string Text { get; set; }
}
[XmlRoot(ElementName = "data_source")]
public class DataSource
{
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
}
[XmlRoot(ElementName = "request")]
public class Request
{
[XmlAttribute(AttributeName = "type")]
public string Type { get; set; }
}
Trying to Deserialise XML response to C#. but getting error as specified below.
My code:
IRestResponse result = Client.Execute<StudentPersonal>(new RestRequest(Method.POST)
.AddHeader("Accept", " application/xml")
.AddHeader("Authorization", "Basic Y2xaTWNqZFFlbFF4YVU1TlFtUnZOV3hXTkhadmNHaFhPSGxTT0Rka1VIcFhhRTl5TWtWQ05rRjNUMlp5VlUxWlNYa3hjbEU1V1RGUmMxTkNOMlZWVlRvNk9nPT06eUkxdERIanNVcGxLUUpzUlNXNTVacXpRVUFGQ3JrZzFwUGxUbDhUTmRQaFU0Z0xsTFJlQkVxTmhzZml3TnpaVA==")
.AddHeader("Content-Type", "application/xml")
.AddParameter("application/xml", body, ParameterType.RequestBody));
StudentPersonal firstResponse = new StudentPersonal();
StringReader srt = new StringReader(result.Content);
XmlSerializer serializer = new XmlSerializer(typeof(StudentPersonal), new XmlRootAttribute("StudentPersonal"));
firstResponse = (StudentPersonal)serializer.Deserialize(srt);
Console.WriteLine(firstResponse);
Assert.AreEqual("Created", result.StatusCode.ToString());
My classes:
[XmlRoot(ElementName = "StudentPersonal")]
public class StudentPersonal
{
//// XmlSerializer serializer = new XmlSerializer(typeof(StudentPersonal));
//// using (StringReader reader = new StringReader(xml))
//// {
//// var test = (StudentPersonal)serializer.Deserialize(reader);
//// }
[XmlElement(ElementName = "LocalId")]
public double LocalId { get; set; }
[XmlElement(ElementName = "StateProvinceId")]
public int StateProvinceId { get; set; }
[XmlElement(ElementName = "ElectronicIdList")]
public object ElectronicIdList { get; set; }
[XmlElement(ElementName = "OtherIdList")]
public OtherIdList OtherIdList { get; set; }
[XmlElement(ElementName = "PersonInfo")]
public PersonInfo PersonInfo { get; set; }
[XmlElement(ElementName = "GiftedTalented")]
public string GiftedTalented { get; set; }
[XmlElement(ElementName = "EconomicDisadvantage")]
public string EconomicDisadvantage { get; set; }
[XmlElement(ElementName = "ESL")]
public string ESL { get; set; }
[XmlElement(ElementName = "YoungCarersRole")]
public string YoungCarersRole { get; set; }
[XmlElement(ElementName = "Disability")]
public string Disability { get; set; }
[XmlElement(ElementName = "IntegrationAide")]
public string IntegrationAide { get; set; }
[XmlElement(ElementName = "EducationSupport")]
public string EducationSupport { get; set; }
[XmlElement(ElementName = "Sensitive")]
public string Sensitive { get; set; }
[XmlAttribute(AttributeName = "xsd")]
public string Xsd { get; set; }
[XmlAttribute(AttributeName = "xsi")]
public string Xsi { get; set; }
[XmlAttribute(AttributeName = "RefId")]
public string RefId { get; set; }
[XmlAttribute(AttributeName = "xmlns")]
public string Xmlns { get; set; }
[XmlText]
public string Text { get; set; }
}
[XmlRoot(ElementName = "OtherId")]
public class OtherId
{
[XmlAttribute(AttributeName = "Type")]
public string Type { get; set; }
[XmlText]
public int Text { get; set; }
}
[XmlRoot(ElementName = "OtherIdList")]
public class OtherIdList
{
[XmlElement(ElementName = "OtherId")]
public List<OtherId> OtherId { get; set; }
}
[XmlRoot(ElementName = "Name")]
public class Name
{
[XmlElement(ElementName = "Title")]
public string Title { get; set; }
[XmlElement(ElementName = "FamilyName")]
public string FamilyName { get; set; }
[XmlElement(ElementName = "GivenName")]
public string GivenName { get; set; }
[XmlElement(ElementName = "MiddleName")]
public string MiddleName { get; set; }
[XmlElement(ElementName = "FamilyNameFirst")]
public string FamilyNameFirst { get; set; }
[XmlElement(ElementName = "PreferredFamilyName")]
public string PreferredFamilyName { get; set; }
[XmlElement(ElementName = "PreferredFamilyNameFirst")]
public string PreferredFamilyNameFirst { get; set; }
[XmlElement(ElementName = "PreferredGivenName")]
public string PreferredGivenName { get; set; }
[XmlElement(ElementName = "FullName")]
public string FullName { get; set; }
[XmlAttribute(AttributeName = "Type")]
public string Type { get; set; }
[XmlText]
public string Text { get; set; }
}
[XmlRoot(ElementName = "EnglishProficiency")]
public class EnglishProficiency
{
[XmlElement(ElementName = "Code")]
public int Code { get; set; }
}
[XmlRoot(ElementName = "Language")]
public class Language
{
[XmlElement(ElementName = "Code")]
public int Code { get; set; }
[XmlElement(ElementName = "LanguageType")]
public int LanguageType { get; set; }
}
[XmlRoot(ElementName = "LanguageList")]
public class LanguageList
{
[XmlElement(ElementName = "Language")]
public List<Language> Language { get; set; }
}
[XmlRoot(ElementName = "DwellingArrangement")]
public class DwellingArrangement
{
[XmlElement(ElementName = "Code")]
public int Code { get; set; }
}
[XmlRoot(ElementName = "Religion")]
public class Religion
{
[XmlElement(ElementName = "Code")]
public int Code { get; set; }
}
[XmlRoot(ElementName = "ReligiousEvent")]
public class ReligiousEvent
{
[XmlElement(ElementName = "Type")]
public string Type { get; set; }
[XmlElement(ElementName = "Date")]
public DateTime Date { get; set; }
}
[XmlRoot(ElementName = "ReligiousEventList")]
public class ReligiousEventList
{
[XmlElement(ElementName = "ReligiousEvent")]
public ReligiousEvent ReligiousEvent { get; set; }
}
[XmlRoot(ElementName = "Demographics")]
public class Demographics
{
[XmlElement(ElementName = "IndigenousStatus")]
public int IndigenousStatus { get; set; }
[XmlElement(ElementName = "Sex")]
public int Sex { get; set; }
[XmlElement(ElementName = "BirthDate")]
public DateTime BirthDate { get; set; }
[XmlElement(ElementName = "BirthDateVerification")]
public int BirthDateVerification { get; set; }
[XmlElement(ElementName = "CountryArrivalDate")]
public DateTime CountryArrivalDate { get; set; }
[XmlElement(ElementName = "EnglishProficiency")]
public EnglishProficiency EnglishProficiency { get; set; }
[XmlElement(ElementName = "LanguageList")]
public LanguageList LanguageList { get; set; }
[XmlElement(ElementName = "DwellingArrangement")]
public DwellingArrangement DwellingArrangement { get; set; }
[XmlElement(ElementName = "Religion")]
public Religion Religion { get; set; }
[XmlElement(ElementName = "ReligiousEventList")]
public ReligiousEventList ReligiousEventList { get; set; }
[XmlElement(ElementName = "PermanentResident")]
public string PermanentResident { get; set; }
[XmlElement(ElementName = "VisaSubClass")]
public int VisaSubClass { get; set; }
[XmlElement(ElementName = "VisaStatisticalCode")]
public string VisaStatisticalCode { get; set; }
[XmlElement(ElementName = "VisaExpiryDate")]
public DateTime VisaExpiryDate { get; set; }
[XmlElement(ElementName = "LBOTE")]
public string LBOTE { get; set; }
[XmlElement(ElementName = "ImmunisationCertificateStatus")]
public string ImmunisationCertificateStatus { get; set; }
[XmlElement(ElementName = "CulturalBackground")]
public int CulturalBackground { get; set; }
[XmlElement(ElementName = "MaritalStatus")]
public int MaritalStatus { get; set; }
[XmlElement(ElementName = "MedicareNumber")]
public int MedicareNumber { get; set; }
}
[XmlRoot(ElementName = "PhoneNumber")]
public class PhoneNumber
{
[XmlElement(ElementName = "Number")]
public int Number { get; set; }
[XmlElement(ElementName = "ListedStatus")]
public string ListedStatus { get; set; }
[XmlAttribute(AttributeName = "Type")]
public int Type { get; set; }
[XmlText]
public string Text { get; set; }
}
[XmlRoot(ElementName = "PhoneNumberList")]
public class PhoneNumberList
{
[XmlElement(ElementName = "PhoneNumber")]
public PhoneNumber PhoneNumber { get; set; }
}
[XmlRoot(ElementName = "Email")]
public class Email
{
[XmlAttribute(AttributeName = "Type")]
public int Type { get; set; }
[XmlText]
public string Text { get; set; }
}
[XmlRoot(ElementName = "EmailList")]
public class EmailList
{
[XmlElement(ElementName = "Email")]
public List<Email> Email { get; set; }
}
[XmlRoot(ElementName = "PersonInfo")]
public class PersonInfo
{
[XmlElement(ElementName = "Name")]
public Name Name { get; set; }
[XmlElement(ElementName = "Demographics")]
public Demographics Demographics { get; set; }
[XmlElement(ElementName = "AddressList")]
public object AddressList { get; set; }
[XmlElement(ElementName = "PhoneNumberList")]
public PhoneNumberList PhoneNumberList { get; set; }
[XmlElement(ElementName = "EmailList")]
public EmailList EmailList { get; set; }
}
Below is the response XML details from Result.content:
<StudentPersonal xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" RefId=\"9ec476fd-09b5-4b2b-967a-fb80b207526e\" xmlns=\"http://www.sifassociation.org/datamodel/au/3.4\">
<LocalId>2432717276450097998</LocalId>
<StateProvinceId>674361</StateProvinceId>
<ElectronicIdList />
<OtherIdList>
<OtherId Type=\"MazeKey\">674363</OtherId>
<OtherId Type=\"VETUSI\">674362</OtherId>
<OtherId Type=\"UPN\">674363</OtherId>
</OtherIdList>
<PersonInfo>
<Name Type=\"LGL\">
<Title>Ms</Title>
<FamilyName>Gutteridge2</FamilyName>
<GivenName>Ferdinanda2</GivenName>
<MiddleName>Creamer1</MiddleName>
<FamilyNameFirst>N</FamilyNameFirst>
<PreferredFamilyName>Gutteridge</PreferredFamilyName>
<PreferredFamilyNameFirst>N</PreferredFamilyNameFirst>
<PreferredGivenName>Ferdinanda</PreferredGivenName>
<FullName> Ferdinanda Gutteridge</FullName>
</Name>
<Demographics>
<IndigenousStatus>1</IndigenousStatus>
<Sex>2</Sex>
<BirthDate>2006-03-21</BirthDate>
<BirthDateVerification>1004</BirthDateVerification>
<CountryArrivalDate>2008-09-17</CountryArrivalDate>
<EnglishProficiency>
<Code>1</Code>
</EnglishProficiency>
<LanguageList>
<Language>
<Code>1201</Code>
<LanguageType>3</LanguageType>
</Language>
<Language>
<Code>4303</Code>
<LanguageType>1</LanguageType>
</Language>
<Language>
<Code>4303</Code>
<LanguageType>1</LanguageType>
</Language>
</LanguageList>
<DwellingArrangement>
<Code>1671</Code>
</DwellingArrangement>
<Religion>
<Code>0002</Code>
</Religion>
<ReligiousEventList>
<ReligiousEvent>
<Type>Confirmation</Type>
<Date>2018-07-17</Date>
</ReligiousEvent>
</ReligiousEventList>
<PermanentResident>P</PermanentResident>
<VisaSubClass>124</VisaSubClass>
<VisaStatisticalCode>VisaStatisticalCode</VisaStatisticalCode>
<VisaExpiryDate>2019-01-17</VisaExpiryDate>
<LBOTE>N</LBOTE>
<ImmunisationCertificateStatus>C</ImmunisationCertificateStatus>
<CulturalBackground>0901</CulturalBackground>
<MaritalStatus>3</MaritalStatus>
<MedicareNumber>67436</MedicareNumber>
</Demographics>
<AddressList />
<PhoneNumberList>
<PhoneNumber Type=\"0350\">
<Number>12367436</Number>
<ListedStatus>U</ListedStatus>
</PhoneNumber>
</PhoneNumberList>
<EmailList>
<Email Type=\"01\">person67436#email1.com.au</Email>
<Email Type=\"02\">person67436#email2.com.au</Email>
<Email Type=\"03\">person67436#email3.com.au</Email>
</EmailList>
</PersonInfo>
<GiftedTalented>N</GiftedTalented>
<EconomicDisadvantage>N</EconomicDisadvantage>
<ESL>N</ESL>
<YoungCarersRole>N</YoungCarersRole>
<Disability>N</Disability>
<IntegrationAide>N</IntegrationAide>
<EducationSupport>U</EducationSupport>
<Sensitive>N</Sensitive>
</StudentPersonal>
Error is from the above XML response. Getting Error
There is an error in XML document (1, 2). InvalidOperationException: <StudentPersonal xmlns='http://www.sifassociation.org/datamodel/au/3.4'> was not expected.
There seems to be two issues.
Add the namespace to your class:
[XmlRoot(ElementName = "StudentPersonal", Namespace = "http://www.sifassociation.org/datamodel/au/3.4")]
public class StudentPersonal
...
In the XML, all " are escaped with \.
<StudentPersonal xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" RefId=\"9ec476fd-09b5-4b2b-967a-fb80b207526e\" xmlns=\"http://www.sifassociation.org/datamodel/au/3.4\">
...
</StudentPersonal>
This also occurs in other places throughout the XML. Such as:
<PhoneNumber Type=\"0350\">
To resolve the issue, replace all occurrences of \" with ".
<StudentPersonal xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" RefId="9ec476fd-09b5-4b2b-967a-fb80b207526e" xmlns="http://www.sifassociation.org/datamodel/au/3.4">
...
</StudentPersonal>
and
<PhoneNumber Type="0350">
Here's a method that can be used to deserialize the XML:
DeserializeXMLStringToObject:
public static T DeserializeXMLStringToObject<T>(string xmlData)
{
T rObject = default(T);
try
{
if (string.IsNullOrEmpty(xmlData))
{
return default(T);
}
//replace \" with "
string xmlDataSanitized = xmlData.Replace("\\\"", "\"");
using (System.IO.StringReader reader = new System.IO.StringReader(xmlDataSanitized))
{
//add the namespace to the class instead of adding it here
//System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T), "http://www.sifassociation.org/datamodel/au/3.4");
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
rObject = (T)serializer.Deserialize(reader);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
throw ex;
}
return rObject;
}
Usage:
private StudentPersonal _studentPersonal = null;
...
_studentPersonal = DeserializeXMLStringToObject<StudentPersonal>(result.Content);
//for testing, display some of the data
//System.Diagnostics.Debug.WriteLine("LocalId: " + _studentPersonal.LocalId);
//System.Diagnostics.Debug.WriteLine("GivenName: " + _studentPersonal.PersonInfo.Name.GivenName);
Sorry for any lq thing, am new to c#.
Am trying to display all dates from XML WEB API...
I already printed for only 1 date, I want for 5 days?
I need to display in Console application all data for 5 days just like I post for one date.
What should I use, can anyone help me please?
replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.
static void Main(string[] args)
{
var clientWeather = new RestClient("http://api.worldweatheronline.com/premium/v1/weather.ashx");//?key=c37f984779f14beb9bf01943201104&q=Pristina&format=json&num_of_days=5");
//client.Timeout = -1;
var requestWeather = new RestRequest(Method.GET);
requestWeather.AddParameter("key", "c37f984779f14beb9bf01943201104", ParameterType.QueryString);
requestWeather.AddParameter("q", "London", ParameterType.QueryString);
requestWeather.AddParameter("format", "xml", ParameterType.QueryString);
requestWeather.AddParameter("num_of_days", "5", ParameterType.QueryString);
IRestResponse responseWeather = clientWeather.Execute(requestWeather);
var xmlDeserializer = new XmlDeserializer();
var place = xmlDeserializer.Deserialize<Request>(responseWeather);
var temp = xmlDeserializer.Deserialize<Current_condition>(responseWeather);
var dit = xmlDeserializer.Deserialize<Weather>(responseWeather);
var data1 = xmlDeserializer.Deserialize<Data>(responseWeather);
Console.WriteLine("Place: " + place.Query);
Console.WriteLine("Temp momentale: " + temp.FeelsLikeC);
Console.WriteLine("Temp for 5 days.");
Console.Write("Date " + "TempMin " );
Console.WriteLine("TempMax");
Console.WriteLine(dit.Date + " " + dit.MintempC + " " + dit.MaxtempC);
Console.ReadLine();
Console.ReadLine();
}
[XmlRoot(ElementName = "request")]
public class Request
{
[XmlElement(ElementName = "type")]
public string Type { get; set; }
[XmlElement(ElementName = "query")]
public string Query { get; set; }
}
[XmlRoot(ElementName = "current_condition")]
public class Current_condition
{
[XmlElement(ElementName = "observation_time")]
public string Observation_time { get; set; }
[XmlElement(ElementName = "temp_C")]
public string Temp_C { get; set; }
[XmlElement(ElementName = "temp_F")]
public string Temp_F { get; set; }
[XmlElement(ElementName = "weatherCode")]
public string WeatherCode { get; set; }
[XmlElement(ElementName = "weatherIconUrl")]
public string WeatherIconUrl { get; set; }
[XmlElement(ElementName = "weatherDesc")]
public string WeatherDesc { get; set; }
[XmlElement(ElementName = "windspeedMiles")]
public string WindspeedMiles { get; set; }
[XmlElement(ElementName = "windspeedKmph")]
public string WindspeedKmph { get; set; }
[XmlElement(ElementName = "winddirDegree")]
public string WinddirDegree { get; set; }
[XmlElement(ElementName = "winddir16Point")]
public string Winddir16Point { get; set; }
[XmlElement(ElementName = "precipMM")]
public string PrecipMM { get; set; }
[XmlElement(ElementName = "precipInches")]
public string PrecipInches { get; set; }
[XmlElement(ElementName = "humidity")]
public string Humidity { get; set; }
[XmlElement(ElementName = "visibility")]
public string Visibility { get; set; }
[XmlElement(ElementName = "visibilityMiles")]
public string VisibilityMiles { get; set; }
[XmlElement(ElementName = "pressure")]
public string Pressure { get; set; }
[XmlElement(ElementName = "pressureInches")]
public string PressureInches { get; set; }
[XmlElement(ElementName = "cloudcover")]
public string Cloudcover { get; set; }
[XmlElement(ElementName = "FeelsLikeC")]
public string FeelsLikeC { get; set; }
[XmlElement(ElementName = "FeelsLikeF")]
public string FeelsLikeF { get; set; }
[XmlElement(ElementName = "uvIndex")]
public string UvIndex { get; set; }
}
[XmlRoot(ElementName = "astronomy")]
public class Astronomy
{
[XmlElement(ElementName = "sunrise")]
public string Sunrise { get; set; }
[XmlElement(ElementName = "sunset")]
public string Sunset { get; set; }
[XmlElement(ElementName = "moonrise")]
public string Moonrise { get; set; }
[XmlElement(ElementName = "moonset")]
public string Moonset { get; set; }
[XmlElement(ElementName = "moon_phase")]
public string Moon_phase { get; set; }
[XmlElement(ElementName = "moon_illumination")]
public string Moon_illumination { get; set; }
}
[XmlRoot(ElementName = "hourly")]
public class Hourly
{
[XmlElement(ElementName = "time")]
public string Time { get; set; }
[XmlElement(ElementName = "tempC")]
public string TempC { get; set; }
[XmlElement(ElementName = "tempF")]
public string TempF { get; set; }
[XmlElement(ElementName = "windspeedMiles")]
public string WindspeedMiles { get; set; }
[XmlElement(ElementName = "windspeedKmph")]
public string WindspeedKmph { get; set; }
[XmlElement(ElementName = "winddirDegree")]
public string WinddirDegree { get; set; }
[XmlElement(ElementName = "winddir16Point")]
public string Winddir16Point { get; set; }
[XmlElement(ElementName = "weatherCode")]
public string WeatherCode { get; set; }
[XmlElement(ElementName = "weatherIconUrl")]
public string WeatherIconUrl { get; set; }
[XmlElement(ElementName = "weatherDesc")]
public string WeatherDesc { get; set; }
[XmlElement(ElementName = "precipMM")]
public string PrecipMM { get; set; }
[XmlElement(ElementName = "precipInches")]
public string PrecipInches { get; set; }
[XmlElement(ElementName = "humidity")]
public string Humidity { get; set; }
[XmlElement(ElementName = "visibility")]
public string Visibility { get; set; }
[XmlElement(ElementName = "visibilityMiles")]
public string VisibilityMiles { get; set; }
[XmlElement(ElementName = "pressure")]
public string Pressure { get; set; }
[XmlElement(ElementName = "pressureInches")]
public string PressureInches { get; set; }
[XmlElement(ElementName = "cloudcover")]
public string Cloudcover { get; set; }
[XmlElement(ElementName = "HeatIndexC")]
public string HeatIndexC { get; set; }
[XmlElement(ElementName = "HeatIndexF")]
public string HeatIndexF { get; set; }
[XmlElement(ElementName = "DewPointC")]
public string DewPointC { get; set; }
[XmlElement(ElementName = "DewPointF")]
public string DewPointF { get; set; }
[XmlElement(ElementName = "WindChillC")]
public string WindChillC { get; set; }
[XmlElement(ElementName = "WindChillF")]
public string WindChillF { get; set; }
[XmlElement(ElementName = "WindGustMiles")]
public string WindGustMiles { get; set; }
[XmlElement(ElementName = "WindGustKmph")]
public string WindGustKmph { get; set; }
[XmlElement(ElementName = "FeelsLikeC")]
public string FeelsLikeC { get; set; }
[XmlElement(ElementName = "FeelsLikeF")]
public string FeelsLikeF { get; set; }
[XmlElement(ElementName = "chanceofrain")]
public string Chanceofrain { get; set; }
[XmlElement(ElementName = "chanceofremdry")]
public string Chanceofremdry { get; set; }
[XmlElement(ElementName = "chanceofwindy")]
public string Chanceofwindy { get; set; }
[XmlElement(ElementName = "chanceofovercast")]
public string Chanceofovercast { get; set; }
[XmlElement(ElementName = "chanceofsunshine")]
public string Chanceofsunshine { get; set; }
[XmlElement(ElementName = "chanceoffrost")]
public string Chanceoffrost { get; set; }
[XmlElement(ElementName = "chanceofhightemp")]
public string Chanceofhightemp { get; set; }
[XmlElement(ElementName = "chanceoffog")]
public string Chanceoffog { get; set; }
[XmlElement(ElementName = "chanceofsnow")]
public string Chanceofsnow { get; set; }
[XmlElement(ElementName = "chanceofthunder")]
public string Chanceofthunder { get; set; }
[XmlElement(ElementName = "uvIndex")]
public string UvIndex { get; set; }
}
[XmlRoot(ElementName = "weather")]
public class Weather
{
[XmlElement(ElementName = "date")]
public string Date { get; set; }
[XmlElement(ElementName = "astronomy")]
public Astronomy Astronomy { get; set; }
[XmlElement(ElementName = "maxtempC")]
public string MaxtempC { get; set; }
[XmlElement(ElementName = "maxtempF")]
public string MaxtempF { get; set; }
[XmlElement(ElementName = "mintempC")]
public string MintempC { get; set; }
[XmlElement(ElementName = "mintempF")]
public string MintempF { get; set; }
[XmlElement(ElementName = "avgtempC")]
public string AvgtempC { get; set; }
[XmlElement(ElementName = "avgtempF")]
public string AvgtempF { get; set; }
[XmlElement(ElementName = "totalSnow_cm")]
public string TotalSnow_cm { get; set; }
[XmlElement(ElementName = "sunHour")]
public string SunHour { get; set; }
[XmlElement(ElementName = "uvIndex")]
public string UvIndex { get; set; }
[XmlElement(ElementName = "hourly")]
public List<Hourly> Hourly { get; set; }
}
[XmlRoot(ElementName = "month")]
public class Month
{
[XmlElement(ElementName = "index")]
public string Index { get; set; }
[XmlElement(ElementName = "name")]
public string Name { get; set; }
[XmlElement(ElementName = "avgMinTemp")]
public string AvgMinTemp { get; set; }
[XmlElement(ElementName = "avgMinTemp_F")]
public string AvgMinTemp_F { get; set; }
[XmlElement(ElementName = "absMaxTemp")]
public string AbsMaxTemp { get; set; }
[XmlElement(ElementName = "absMaxTemp_F")]
public string AbsMaxTemp_F { get; set; }
[XmlElement(ElementName = "avgDailyRainfall")]
public string AvgDailyRainfall { get; set; }
}
[XmlRoot(ElementName = "ClimateAverages")]
public class ClimateAverages
{
[XmlElement(ElementName = "month")]
public List<Month> Month { get; set; }
}
[XmlRoot(ElementName = "data")]
public class Data
{
[XmlElement(ElementName = "request")]
public Request Request { get; set; }
[XmlElement(ElementName = "current_condition")]
public Current_condition Current_condition { get; set; }
[XmlElement(ElementName = "weather")]
public List<Weather> Weather { get; set; }
[XmlElement(ElementName = "ClimateAverages")]
public ClimateAverages ClimateAverages { get; set; }
}
}
}
You can deserialize xml to a collection of specific objects, like this:
//request and response code omitted for brevity
var dit = xmlDeserializer.Deserialize<List<Weather>>(responseWeather);
foreach(var date in dit)
{
Console.WriteLine(date.Date + " " + date.MintempC + " " + date.MaxtempC);
}
output:
2020-04-20 9 15
2020-04-21 9 15
2020-04-22 11 16
2020-04-23 12 20
2020-04-24 11 19
I modified the URL. You were getting json and not xml. See xml linq below :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Net;
namespace ConsoleApplication1
{
class Program
{
const string URL = "http://api.worldweatheronline.com/premium/v1/weather.ashx?key=c37f984779f14beb9bf01943201104&q=Pristina&num_of_days=5";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(URL);
List<TemperatureDate> dates = doc.Descendants("weather").Select(x => new TemperatureDate()
{
date = (DateTime)x.Element("date"),
avgtempF = (int)x.Element("avgtempF"),
hourTemp = x.Elements("hourly").Select(y => new KeyValuePair<int,int>(((int)y.Element("time"))/100, (int)y.Element("tempF"))).ToList()
}).ToList();
}
}
public class TemperatureDate
{
public DateTime date { get; set; }
public int avgtempF { get; set; }
public List<KeyValuePair<int, int>> hourTemp { get; set; }
}
}
using serialization
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
const string URL = "http://api.worldweatheronline.com/premium/v1/weather.ashx?key=c37f984779f14beb9bf01943201104&q=Pristina&num_of_days=5";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(URL);
XmlSerializer serializer = new XmlSerializer(typeof(data));
data data = (data)serializer.Deserialize(reader);
}
}
public class data
{
public request request { get; set; }
public current_condition current_condition { get; set; }
public weather weather { get; set; }
}
public class request
{
[XmlElement("type")]
public string _type { get; set; }
public string query { get; set; }
}
public class current_condition
{
public TimeSpan observation_time { get; set; }
public int temp_C { get; set; }
public int temp_F { get; set; }
public int weatherCode { get; set; }
public string weatherIconUrl { get; set; }
public string weatherDesc { get; set; }
public int windspeedMiles { get; set; }
public int windspeedKmph { get; set; }
public int winddirDegree { get; set; }
public string winddir16Point { get; set; }
public decimal precipMM { get; set; }
public decimal precipInches { get; set; }
public int humidity { get; set; }
public int visibility { get; set; }
public int visibilityMiles { get; set; }
public int pressure { get; set; }
public int pressureInches { get; set; }
public int cloudcover { get; set; }
public int FeelsLikeC { get; set; }
public int FeelsLikeF { get; set; }
public int uvIndex { get; set; }
}
public class weather
{
public DateTime date { get; set; }
public astronomy astronomy { get; set; }
public int maxtempC { get; set; }
public int maxtempF { get; set; }
public int mintempC { get; set; }
public int mintempF { get; set; }
public int avgtempC { get; set; }
public int avgtempF { get; set; }
public decimal totalSnow_cm { get; set; }
public decimal sunHour { get; set; }
public int uvIndex { get; set; }
[XmlElement("hourly")]
public List<hourly> hourly { get; set; }
}
public class astronomy
{
public TimeSpan sunrise { get; set; }
public TimeSpan sunset { get; set; }
public TimeSpan moonrise { get; set; }
public TimeSpan moonset { get; set; }
public string moon_phase { get; set; }
public int moon_illumination { get; set; }
}
public class hourly
{
public int time { get; set; }
public int tempC { get; set; }
public int tempF { get; set; }
public int windspeedMiles { get; set; }
public int windspeedKmph { get; set; }
public int winddirDegree { get; set; }
public string winddir16Point { get; set; }
public int weatherCode { get; set; }
public string weatherIconUrl { get; set; }
public string weatherDesc { get; set; }
public decimal precipMM { get; set; }
public decimal precipInches { get; set; }
public int humidity { get; set; }
public int visibility { get; set; }
public int visibilityMiles { get; set; }
public int pressure { get; set; }
public int pressureInches { get; set; }
public int cloudcover { get; set; }
public int HeatIndexC { get; set; }
public int HeatIndexF { get; set; }
public int DewPointC { get; set; }
public int DewPointF { get; set; }
public int WindChillC { get; set; }
public int WindChillF { get; set; }
public int WindGustMiles { get; set; }
public int WindGustKmph { get; set; }
public int FeelsLikeC { get; set; }
public int FeelsLikeF { get; set; }
public int chanceofrain { get; set; }
public int chanceofremdry { get; set; }
public int chanceofwindy { get; set; }
public int chanceofovercast { get; set; }
public int chanceofsunshine { get; set; }
public int chanceoffrost { get; set; }
public int chanceofhightemp { get; set; }
public int chanceoffog { get; set; }
public int chanceofsnow { get; set; }
public int chanceofthunder { get; set; }
public int uvIndex { get; set; }
}
}
I have the following xml file which I have tried to load using method to turn it into a business object however it says expecting > at line 1 ,40 but when I look at it looks fine.
XmlSerializer serializer = new XmlSerializer(typeof( SalesOrderXml));
using (TextReader reader = new StringReader(testData))
{
SalesOrderXmlresult = (SalesOrderXml) serializer.Deserialize(reader);
}
Xml here cause of the length of it it would have exceeded the article.
https://pastebin.com/pepp1QDe
I do not no what i am doing wrong as I used the online xml to poco generator to help me out as a its a long file.
Any tips of what i might be doing wrong I checked for hidden chars in the file and there is none.
public class SalesOrderXml
{
[XmlRoot(ElementName = "ORDER_ITEM")]
public class ORDER_ITEM
{
[XmlElement(ElementName = "PRODUCT_ID")]
public string PRODUCT_ID { get; set; }
[XmlElement(ElementName = "STOCK_CODE")]
public string STOCK_CODE { get; set; }
[XmlElement(ElementName = "ITEM_TYPE")]
public string ITEM_TYPE { get; set; }
[XmlElement(ElementName = "DESCRIPTION")]
public string DESCRIPTION { get; set; }
[XmlElement(ElementName = "QUANTITY")]
public string QUANTITY { get; set; }
[XmlElement(ElementName = "PRICE")]
public string PRICE { get; set; }
[XmlElement(ElementName = "HEIGHT")]
public string HEIGHT { get; set; }
[XmlElement(ElementName = "WIDTH")]
public string WIDTH { get; set; }
[XmlElement(ElementName = "HINGE_HOLES")]
public string HINGE_HOLES { get; set; }
[XmlElement(ElementName = "DRILL_TOP")]
public string DRILL_TOP { get; set; }
[XmlElement(ElementName = "DRILL_BOTTOM")]
public string DRILL_BOTTOM { get; set; }
[XmlElement(ElementName = "DRILL_TOP_1")]
public string DRILL_TOP_1 { get; set; }
[XmlElement(ElementName = "DRILL_TOP_2")]
public string DRILL_TOP_2 { get; set; }
[XmlElement(ElementName = "DRILL_TOP_3")]
public string DRILL_TOP_3 { get; set; }
[XmlElement(ElementName = "RAW")]
public string RAW { get; set; }
[XmlElement(ElementName = "RAH")]
public string RAH { get; set; }
[XmlElement(ElementName = "LAW")]
public string LAW { get; set; }
[XmlElement(ElementName = "LAH")]
public string LAH { get; set; }
[XmlElement(ElementName = "FRAME_TYPE")]
public string FRAME_TYPE { get; set; }
[XmlElement(ElementName = "GLAZING_TYPE")]
public string GLAZING_TYPE { get; set; }
[XmlElement(ElementName = "LENGTH")]
public string LENGTH { get; set; }
[XmlElement(ElementName = "DEPTH")]
public string DEPTH { get; set; }
[XmlElement(ElementName = "CORNER_POSITION")]
public string CORNER_POSITION { get; set; }
[XmlElement(ElementName = "HORIZONTAL_GRAIN")]
public string HORIZONTAL_GRAIN { get; set; }
[XmlElement(ElementName = "PANEL_TYPE")]
public string PANEL_TYPE { get; set; }
[XmlElement(ElementName = "PANEL_EDGE")]
public string PANEL_EDGE { get; set; }
[XmlElement(ElementName = "PROFILED_EDGE")]
public string PROFILED_EDGE { get; set; }
[XmlElement(ElementName = "PROFILED_EDGE_FRONT")]
public string PROFILED_EDGE_FRONT { get; set; }
[XmlElement(ElementName = "PROFILED_EDGE_BACK")]
public string PROFILED_EDGE_BACK { get; set; }
[XmlElement(ElementName = "PROFILED_EDGE_LEFT")]
public string PROFILED_EDGE_LEFT { get; set; }
[XmlElement(ElementName = "PROFILED_EDGE_RIGHT")]
public string PROFILED_EDGE_RIGHT { get; set; }
[XmlElement(ElementName = "EDGE_TYPE")]
public string EDGE_TYPE { get; set; }
[XmlElement(ElementName = "ANGLES_REQUIRED")]
public string ANGLES_REQUIRED { get; set; }
[XmlElement(ElementName = "ANGLE_LENGTH")]
public string ANGLE_LENGTH { get; set; }
[XmlElement(ElementName = "ANGLE_DEPTH")]
public string ANGLE_DEPTH { get; set; }
[XmlElement(ElementName = "THICKNESS")]
public string THICKNESS { get; set; }
[XmlElement(ElementName = "REVERSE_COLOUR")]
public string REVERSE_COLOUR { get; set; }
}
[XmlRoot(ElementName = "DELIVERY_ADDRESS")]
public class DELIVERY_ADDRESS
{
[XmlElement(ElementName = "ADDRESS1")]
public string ADDRESS1 { get; set; }
[XmlElement(ElementName = "ADDRESS2")]
public string ADDRESS2 { get; set; }
[XmlElement(ElementName = "TOWN")]
public string TOWN { get; set; }
[XmlElement(ElementName = "POSTCODE")]
public string POSTCODE { get; set; }
[XmlElement(ElementName = "COUNTY")]
public string COUNTY { get; set; }
[XmlElement(ElementName = "COUNTRY")]
public string COUNTRY { get; set; }
}
[XmlRoot(ElementName = "ORDER")]
public class ORDER
{
[XmlElement(ElementName = "ORDER_ID")]
public string ORDER_ID { get; set; }
[XmlElement(ElementName = "ORDERED_BY")]
public string ORDERED_BY { get; set; }
[XmlElement(ElementName = "ORDER_REFERENCE")]
public string ORDER_REFERENCE { get; set; }
[XmlElement(ElementName = "CUSTOMER_ID")]
public string CUSTOMER_ID { get; set; }
[XmlElement(ElementName = "ACCOUNT_REFERENCE")]
public string ACCOUNT_REFERENCE { get; set; }
[XmlElement(ElementName = "ORDER_TYPE")]
public string ORDER_TYPE { get; set; }
[XmlElement(ElementName = "ORDER_RANGE")]
public string ORDER_RANGE { get; set; }
[XmlElement(ElementName = "ORDER_COLOUR")]
public string ORDER_COLOUR { get; set; }
[XmlElement(ElementName = "EDGE_TYPE")]
public string EDGE_TYPE { get; set; }
[XmlElement(ElementName = "REVERSE_COLOUR")]
public string REVERSE_COLOUR { get; set; }
[XmlElement(ElementName = "HORIZONTAL_GRAIN")]
public string HORIZONTAL_GRAIN { get; set; }
[XmlElement(ElementName = "HANDLE_TYPE")]
public string HANDLE_TYPE { get; set; }
[XmlElement(ElementName = "NOTES")]
public string NOTES { get; set; }
[XmlElement(ElementName = "ORDER_DATE")]
public string ORDER_DATE { get; set; }
[XmlElement(ElementName = "DELIVERY_DATE")]
public string DELIVERY_DATE { get; set; }
[XmlElement(ElementName = "ADDITIONAL_DELIVERY_INFO")]
public string ADDITIONAL_DELIVERY_INFO { get; set; }
[XmlElement(ElementName = "ORDER_ITEM")]
public List<ORDER_ITEM> ORDER_ITEM { get; set; }
[XmlElement(ElementName = "DELIVERY_ADDRESS")]
public DELIVERY_ADDRESS DELIVERY_ADDRESS { get; set; }
[XmlElement(ElementName = "DELIVERY_TYPE")]
public string DELIVERY_TYPE { get; set; }
[XmlElement(ElementName = "DELIVERY_PRICE")]
public string DELIVERY_PRICE { get; set; }
[XmlElement(ElementName = "DELIVERY_CODE")]
public string DELIVERY_CODE { get; set; }
[XmlElement(ElementName = "TOTAL_EX_VAT")]
public string TOTAL_EX_VAT { get; set; }
[XmlElement(ElementName = "TOTAL_INC_VAT")]
public string TOTAL_INC_VAT { get; set; }
[XmlElement(ElementName = "TOTAL_INC_DELIVERY")]
public string TOTAL_INC_DELIVERY { get; set; }
}
}
Although I didn't get the same error as you when I setup a test case using your code, I did get an error about "ORDER" being unexpected.
I then successfully deserialized the XML by specifying SalesOrderXml.ORDER as the root class, rather than SalesOrderXml.
XmlSerializer serializer = new XmlSerializer(typeof(SalesOrderXml.ORDER));
using (TextReader reader = new StringReader(testData))
{
var ob = (SalesOrderXml.ORDER)serializer.Deserialize(reader);
}
I set testData exactly the same as your pastebin string (with the spaces trimmed as per Renzo's comment), and my test case ran successfully.
I have deserialized the XML Response from API, now I need to display the deserialized objects to list in ASP.NET MVC View.
XML Response:
<AvailabilityOutbound>...</AvailabilityOutbound>
<AvailabilityReturn>...</AvailabilityReturn>
</Availability>
Controller:
public ActionResult Create([Bind(Include="FlightId,Origin,Destination,DepartFromDate,DepartToDate,ReturnFromDate,ReturnToDate,AdultPax,ChildPax,Language")] FlightAvailibility flightavailibility)
{
if (ModelState.IsValid)
{
BookingServiceReference.BookingService newBooking= new BookingServiceReference.BookingService();
string xmlResult = string.Empty;
xmlResult = newBooking.FlightAvailability("TESTAPI", "TESTAPI", flightavailibility.Origin, flightavailibility.Destination,
flightavailibility.DepartFromDate, flightavailibility.DepartToDate, flightavailibility.ReturnFromDate, flightavailibility.ReturnToDate,
flightavailibility.AdultPax, flightavailibility.ChildPax, 0, 0, null, null, null, "NP");
// return this.Content(xmlResult, "text/xml");
XmlSerializer serializer = new XmlSerializer(typeof(Availability));
using (StringReader reader = new StringReader(xmlResult))
{
Availability deserialized = (Availability)serializer.Deserialize(reader);
ViewBag.NewList = deserialized;
return View(deserialized);
}
}
return RedirectToAction("Index");
}
and the Model for class.
namespace YetiAirlinesProjectDev.Models
{
[XmlRoot(ElementName = "AvailabilityFlight")]
public class AvailabilityFlight
{
[XmlElement(ElementName = "airline_rcd")]
public string Airline_rcd { get; set; }
[XmlElement(ElementName = "flight_number")]
public string Flight_number { get; set; }
[XmlElement(ElementName = "booking_class_rcd")]
public string Booking_class_rcd { get; set; }
[XmlElement(ElementName = "boarding_class_rcd")]
public string Boarding_class_rcd { get; set; }
[XmlElement(ElementName = "flight_id")]
public string Flight_id { get; set; }
[XmlElement(ElementName = "origin_rcd")]
public string Origin_rcd { get; set; }
[XmlElement(ElementName = "destination_rcd")]
public string Destination_rcd { get; set; }
[XmlElement(ElementName = "origin_name")]
public string Origin_name { get; set; }
[XmlElement(ElementName = "destination_name")]
public string Destination_name { get; set; }
[XmlElement(ElementName = "flight_status_rcd")]
public string Flight_status_rcd { get; set; }
[XmlElement(ElementName = "departure_date")]
public string Departure_date { get; set; }
[XmlElement(ElementName = "planned_departure_time")]
public string Planned_departure_time { get; set; }
[XmlElement(ElementName = "planned_arrival_time")]
public string Planned_arrival_time { get; set; }
[XmlElement(ElementName = "fare_id")]
public string Fare_id { get; set; }
[XmlElement(ElementName = "fare_code")]
public string Fare_code { get; set; }
[XmlElement(ElementName = "transit_points")]
public string Transit_points { get; set; }
[XmlElement(ElementName = "transit_points_name")]
public string Transit_points_name { get; set; }
[XmlElement(ElementName = "transit_flight_id")]
public string Transit_flight_id { get; set; }
[XmlElement(ElementName = "transit_booking_class_rcd")]
public string Transit_booking_class_rcd { get; set; }
[XmlElement(ElementName = "transit_boarding_class_rcd")]
public string Transit_boarding_class_rcd { get; set; }
[XmlElement(ElementName = "transit_airport_rcd")]
public string Transit_airport_rcd { get; set; }
[XmlElement(ElementName = "transit_departure_date")]
public string Transit_departure_date { get; set; }
[XmlElement(ElementName = "transit_planned_departure_time")]
public string Transit_planned_departure_time { get; set; }
[XmlElement(ElementName = "transit_planned_arrival_time")]
public string Transit_planned_arrival_time { get; set; }
[XmlElement(ElementName = "transit_fare_id")]
public string Transit_fare_id { get; set; }
[XmlElement(ElementName = "transit_name")]
public string Transit_name { get; set; }
[XmlElement(ElementName = "transit_waitlist_open_flag")]
public string Transit_waitlist_open_flag { get; set; }
[XmlElement(ElementName = "transit_airline_rcd")]
public string Transit_airline_rcd { get; set; }
[XmlElement(ElementName = "transit_flight_number")]
public string Transit_flight_number { get; set; }
[XmlElement(ElementName = "transit_flight_status_rcd")]
public string Transit_flight_status_rcd { get; set; }
[XmlElement(ElementName = "transit_flight_duration")]
public string Transit_flight_duration { get; set; }
[XmlElement(ElementName = "transit_class_open_flag")]
public string Transit_class_open_flag { get; set; }
[XmlElement(ElementName = "transit_nesting_string")]
public string Transit_nesting_string { get; set; }
[XmlElement(ElementName = "nesting_string")]
public string Nesting_string { get; set; }
[XmlElement(ElementName = "full_flight_flag")]
public string Full_flight_flag { get; set; }
[XmlElement(ElementName = "class_open_flag")]
public string Class_open_flag { get; set; }
[XmlElement(ElementName = "close_web_sales")]
public string Close_web_sales { get; set; }
[XmlElement(ElementName = "total_adult_fare")]
public string Total_adult_fare { get; set; }
[XmlElement(ElementName = "total_child_fare")]
public string Total_child_fare { get; set; }
[XmlElement(ElementName = "total_infant_fare")]
public string Total_infant_fare { get; set; }
[XmlElement(ElementName = "fare_column")]
public string Fare_column { get; set; }
[XmlElement(ElementName = "flight_comment")]
public string Flight_comment { get; set; }
[XmlElement(ElementName = "filter_logic_flag")]
public string Filter_logic_flag { get; set; }
[XmlElement(ElementName = "restriction_text")]
public string Restriction_text { get; set; }
[XmlElement(ElementName = "flight_duration")]
public string Flight_duration { get; set; }
[XmlElement(ElementName = "class_capacity")]
public string Class_capacity { get; set; }
[XmlElement(ElementName = "waitlist_open_flag")]
public string Waitlist_open_flag { get; set; }
[XmlElement(ElementName = "refundable_flag")]
public string Refundable_flag { get; set; }
[XmlElement(ElementName = "currency_rcd")]
public string Currency_rcd { get; set; }
[XmlElement(ElementName = "aircraft_type_rcd")]
public string Aircraft_type_rcd { get; set; }
[XmlElement(ElementName = "transit_aircraft_type_rcd")]
public string Transit_aircraft_type_rcd { get; set; }
[XmlElement(ElementName = "arrival_date")]
public string Arrival_date { get; set; }
[XmlElement(ElementName = "transit_arrival_date")]
public string Transit_arrival_date { get; set; }
[XmlElement(ElementName = "number_of_stops")]
public string Number_of_stops { get; set; }
[XmlElement(ElementName = "eticket_flag")]
public string Eticket_flag { get; set; }
[XmlElement(ElementName = "nest_seat_availabile")]
public string Nest_seat_availabile { get; set; }
[XmlElement(ElementName = "endorsement_text")]
public string Endorsement_text { get; set; }
}
[XmlRoot(ElementName = "AvailabilityOutbound")]
public class AvailabilityOutbound
{
[XmlElement(ElementName = "AvailabilityFlight")]
public List<AvailabilityFlight> AvailabilityFlight { get; set; }
}
[XmlRoot(ElementName = "AvailabilityReturn")]
public class AvailabilityReturn
{
[XmlElement(ElementName = "AvailabilityFlight")]
public List<AvailabilityFlight> AvailabilityFlight { get; set; }
}
[XmlRoot(ElementName = "Availability")]
public class Availability
{
[XmlElement(ElementName = "AvailabilityOutbound")]
public AvailabilityOutbound AvailabilityOutbound { get; set; }
[XmlElement(ElementName = "AvailabilityReturn")]
public AvailabilityReturn AvailabilityReturn { get; set; }
}
}
Model for FlightAvailibility:
public class FlightAvailibility
{
public int FlightId { get; set; }
public string Origin { get; set; }
public string Destination { get; set; }
public string DepartFromDate { get; set; }
public string DepartToDate { get; set; }
public string ReturnFromDate { get; set; }
public string ReturnToDate { get; set; }
public short AdultPax { get; set; }
public short ChildPax { get; set; }
public string Language { get; set; }
}
Controller:
public ActionResult Index()
{
return View();
}
I want to show the availability List In Index View:
Index.cshtml
I have deserialized the XML Response from API, now I need to display the deserialized objects to list in ASP.NET MVC View.
XML Response:
<AvailabilityOutbound>...</AvailabilityOutbound>
<AvailabilityReturn>...</AvailabilityReturn>
</Availability>
Controller:
public ActionResult Create([Bind(Include="FlightId,Origin,Destination,DepartFromDate,DepartToDate,ReturnFromDate,ReturnToDate,AdultPax,ChildPax,Language")] FlightAvailibility flightavailibility)
{
if (ModelState.IsValid)
{
BookingServiceReference.BookingService newBooking= new BookingServiceReference.BookingService();
string xmlResult = string.Empty;
xmlResult = newBooking.FlightAvailability("TESTAPI", "TESTAPI", flightavailibility.Origin, flightavailibility.Destination,
flightavailibility.DepartFromDate, flightavailibility.DepartToDate, flightavailibility.ReturnFromDate, flightavailibility.ReturnToDate,
flightavailibility.AdultPax, flightavailibility.ChildPax, 0, 0, null, null, null, "NP");
// return this.Content(xmlResult, "text/xml");
XmlSerializer serializer = new XmlSerializer(typeof(Availability));
using (StringReader reader = new StringReader(xmlResult))
{
Availability deserialized = (Availability)serializer.Deserialize(reader);
ViewBag.NewList = deserialized;
return View(deserialized);
}
}
return RedirectToAction("Index");
}
and the Model for class.
namespace YetiAirlinesProjectDev.Models
{
[XmlRoot(ElementName = "AvailabilityFlight")]
public class AvailabilityFlight
{
[XmlElement(ElementName = "airline_rcd")]
public string Airline_rcd { get; set; }
[XmlElement(ElementName = "flight_number")]
public string Flight_number { get; set; }
[XmlElement(ElementName = "booking_class_rcd")]
public string Booking_class_rcd { get; set; }
[XmlElement(ElementName = "boarding_class_rcd")]
public string Boarding_class_rcd { get; set; }
[XmlElement(ElementName = "flight_id")]
public string Flight_id { get; set; }
[XmlElement(ElementName = "origin_rcd")]
public string Origin_rcd { get; set; }
[XmlElement(ElementName = "destination_rcd")]
public string Destination_rcd { get; set; }
[XmlElement(ElementName = "origin_name")]
public string Origin_name { get; set; }
[XmlElement(ElementName = "destination_name")]
public string Destination_name { get; set; }
[XmlElement(ElementName = "flight_status_rcd")]
public string Flight_status_rcd { get; set; }
[XmlElement(ElementName = "departure_date")]
public string Departure_date { get; set; }
[XmlElement(ElementName = "planned_departure_time")]
public string Planned_departure_time { get; set; }
[XmlElement(ElementName = "planned_arrival_time")]
public string Planned_arrival_time { get; set; }
[XmlElement(ElementName = "fare_id")]
public string Fare_id { get; set; }
[XmlElement(ElementName = "fare_code")]
public string Fare_code { get; set; }
[XmlElement(ElementName = "transit_points")]
public string Transit_points { get; set; }
[XmlElement(ElementName = "transit_points_name")]
public string Transit_points_name { get; set; }
[XmlElement(ElementName = "transit_flight_id")]
public string Transit_flight_id { get; set; }
[XmlElement(ElementName = "transit_booking_class_rcd")]
public string Transit_booking_class_rcd { get; set; }
[XmlElement(ElementName = "transit_boarding_class_rcd")]
public string Transit_boarding_class_rcd { get; set; }
[XmlElement(ElementName = "transit_airport_rcd")]
public string Transit_airport_rcd { get; set; }
[XmlElement(ElementName = "transit_departure_date")]
public string Transit_departure_date { get; set; }
[XmlElement(ElementName = "transit_planned_departure_time")]
public string Transit_planned_departure_time { get; set; }
[XmlElement(ElementName = "transit_planned_arrival_time")]
public string Transit_planned_arrival_time { get; set; }
[XmlElement(ElementName = "transit_fare_id")]
public string Transit_fare_id { get; set; }
[XmlElement(ElementName = "transit_name")]
public string Transit_name { get; set; }
[XmlElement(ElementName = "transit_waitlist_open_flag")]
public string Transit_waitlist_open_flag { get; set; }
[XmlElement(ElementName = "transit_airline_rcd")]
public string Transit_airline_rcd { get; set; }
[XmlElement(ElementName = "transit_flight_number")]
public string Transit_flight_number { get; set; }
[XmlElement(ElementName = "transit_flight_status_rcd")]
public string Transit_flight_status_rcd { get; set; }
[XmlElement(ElementName = "transit_flight_duration")]
public string Transit_flight_duration { get; set; }
[XmlElement(ElementName = "transit_class_open_flag")]
public string Transit_class_open_flag { get; set; }
[XmlElement(ElementName = "transit_nesting_string")]
public string Transit_nesting_string { get; set; }
[XmlElement(ElementName = "nesting_string")]
public string Nesting_string { get; set; }
[XmlElement(ElementName = "full_flight_flag")]
public string Full_flight_flag { get; set; }
[XmlElement(ElementName = "class_open_flag")]
public string Class_open_flag { get; set; }
[XmlElement(ElementName = "close_web_sales")]
public string Close_web_sales { get; set; }
[XmlElement(ElementName = "total_adult_fare")]
public string Total_adult_fare { get; set; }
[XmlElement(ElementName = "total_child_fare")]
public string Total_child_fare { get; set; }
[XmlElement(ElementName = "total_infant_fare")]
public string Total_infant_fare { get; set; }
[XmlElement(ElementName = "fare_column")]
public string Fare_column { get; set; }
[XmlElement(ElementName = "flight_comment")]
public string Flight_comment { get; set; }
[XmlElement(ElementName = "filter_logic_flag")]
public string Filter_logic_flag { get; set; }
[XmlElement(ElementName = "restriction_text")]
public string Restriction_text { get; set; }
[XmlElement(ElementName = "flight_duration")]
public string Flight_duration { get; set; }
[XmlElement(ElementName = "class_capacity")]
public string Class_capacity { get; set; }
[XmlElement(ElementName = "waitlist_open_flag")]
public string Waitlist_open_flag { get; set; }
[XmlElement(ElementName = "refundable_flag")]
public string Refundable_flag { get; set; }
[XmlElement(ElementName = "currency_rcd")]
public string Currency_rcd { get; set; }
[XmlElement(ElementName = "aircraft_type_rcd")]
public string Aircraft_type_rcd { get; set; }
[XmlElement(ElementName = "transit_aircraft_type_rcd")]
public string Transit_aircraft_type_rcd { get; set; }
[XmlElement(ElementName = "arrival_date")]
public string Arrival_date { get; set; }
[XmlElement(ElementName = "transit_arrival_date")]
public string Transit_arrival_date { get; set; }
[XmlElement(ElementName = "number_of_stops")]
public string Number_of_stops { get; set; }
[XmlElement(ElementName = "eticket_flag")]
public string Eticket_flag { get; set; }
[XmlElement(ElementName = "nest_seat_availabile")]
public string Nest_seat_availabile { get; set; }
[XmlElement(ElementName = "endorsement_text")]
public string Endorsement_text { get; set; }
}
[XmlRoot(ElementName = "AvailabilityOutbound")]
public class AvailabilityOutbound
{
[XmlElement(ElementName = "AvailabilityFlight")]
public List<AvailabilityFlight> AvailabilityFlight { get; set; }
}
[XmlRoot(ElementName = "AvailabilityReturn")]
public class AvailabilityReturn
{
[XmlElement(ElementName = "AvailabilityFlight")]
public List<AvailabilityFlight> AvailabilityFlight { get; set; }
}
[XmlRoot(ElementName = "Availability")]
public class Availability
{
[XmlElement(ElementName = "AvailabilityOutbound")]
public AvailabilityOutbound AvailabilityOutbound { get; set; }
[XmlElement(ElementName = "AvailabilityReturn")]
public AvailabilityReturn AvailabilityReturn { get; set; }
}
}
Model for FlightAvailibility:
public class FlightAvailibility
{
public int FlightId { get; set; }
public string Origin { get; set; }
public string Destination { get; set; }
public string DepartFromDate { get; set; }
public string DepartToDate { get; set; }
public string ReturnFromDate { get; set; }
public string ReturnToDate { get; set; }
public short AdultPax { get; set; }
public short ChildPax { get; set; }
public string Language { get; set; }
}
Controller:
public ActionResult Index()
{
return View();
}
I want to show the availability List In Index View:
Index.cshtml
#model {YetiAirlinesProjectDev.Models.Availability objnew = (YetiAirlinesProjectDev.Models.Availability)ViewBag.NewList}
<table class="table">
<tr>
<th>
#Html.Display("Aircraft Name")
</th>
</tr>
#foreach (var item in objnew) {
<tr>
<td>
#item
</td>
</tr>
}
</table>
I need to represent the list of availability: AvailabilityOutbound & AvailabilityReturn using Viewbag in Asp.Net MVC View i.e Index Page. I get difficulty passing the Viewbag contents to View i.e Index. My code is not workable in View. I tried a lot. Please help me guys.
First you get you data from api in xml format and then JavaScriptSerializer and make class to pass data to model.In this code the rentlisting action get list from api and show on the view pass list to the view in GetRentListing() function get the api data and last class show they convert the api data to class object and show in view model.
public ActionResult RentListing()
{
if (Session["rentlist"] != null)
{
var list = (List<RootObject>)Session["rentlist"];
return View(list);
}
else
{
var value = GetRentListing();
var list = (List<RootObject>)Session["rentlist"];
return View(list);
}
}
[HttpGet]
public async System.Threading.Tasks.Task<string> GetRentListing()
{
try
{
HttpClient client = new HttpClient();
string AccessCode = ConfigurationManager.AppSettings["AccessCode"];
string GroupCode = ConfigurationManager.AppSettings["GroupCode"];
string Url = "http://www.airlist.com/v1.1/website.asmx/RentListings?AccessCode=" + AccessCode + "&GroupCode=" + GroupCode + "&unitId=" + "" + "&StartPriceRange=" + "" + "&EndPriceRange=" + "" + "&floorAreaMin=" + "" + "&floorAreaMax=" + "" + "&cityId=" + "" + "&unitTypeId=" + "" + "&BedroomsMin=" + "" + "&BedroomsMax=" + "" + "&CommunityId=" + "" + "";
client.BaseAddress = new Uri(Url);
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync(Url).Result;
string data = "false";
if (response.IsSuccessStatusCode)
{
data = await response.Content.ReadAsStringAsync();
XmlDocument doc = new XmlDocument();
doc.LoadXml(data);
string json = Newtonsoft.Json.JsonConvert.SerializeXmlNode(doc);
var list = new JavaScriptSerializer().Deserialize<dynamic>(json);
var d = ((list["RentListings"])["RentListing"]);
var lists = new JavaScriptSerializer().Serialize(d);
lists = lists.Replace("#cdata-section", "cdata");
var listss = new JavaScriptSerializer().Deserialize<List<RootObject>>(lists);
Session["rentlist"] = listss;
}
return data;
}
catch (Exception e)
{
throw;
}
}
public class RootObject
{
public string Count { get; set; }
public string Country { get; set; }
public object State { get; set; }
public string City { get; set; }
public object District { get; set; }
}