I am getting the List of Links in a raw string value, Is there a way to parse the raws string to a list of objects?
Eg: Raw value: <links><link id="{xxxxx-xxx-xxx}" linkid="xxxxx-xxx-xxx" text="Visit" linktype="internal" target="blank" title="Visit" querystring="" linktext="Visit" /><link id="{xxxx-xxx-xxx}" linkid="xxxx-xxx-xxx" text="Apply" linktype="internal" target="blank" title="Apply" querystring="" linktext="Apply" /></links>
To
public IEnumerable<Link> Links {get;set;}
try this
var xml=#"<links><link id='{xxxxx-xxx-xxx}' linkid='xxxxx-xxx-xxx' text='Visit' linktype='internal' target='blank' title='Visit' querystring='' linktext='Visit' /><link id='{xxxx-xxx-xxx}' linkid='xxxx-xxx-xxx' text='Apply' linktype='internal' target='blank' title='Apply' querystring='' linktext='Apply' /></links>";
......
using System.Xml.Serialization;
var serializer = new XmlSerializer(typeof(Links));
Links links;
using (StringReader reader = new StringReader(xml))
{
links = (Links)serializer.Deserialize(reader);
}
foreach (var link in links.Link)
{
Console.WriteLine($"Id: {link.Id} Text: {link.Text} ");
}
}
output
Id: {xxxxx-xxx-xxx} Text: Visit
Id: {xxxx-xxx-xxx} Text: Apply
classes
[XmlRoot(ElementName = "link")]
public class Link
{
[XmlAttribute(AttributeName = "id")]
public string Id { get; set; }
[XmlAttribute(AttributeName = "linkid")]
public string Linkid { get; set; }
[XmlAttribute(AttributeName = "text")]
public string Text { get; set; }
[XmlAttribute(AttributeName = "linktype")]
public string Linktype { get; set; }
[XmlAttribute(AttributeName = "target")]
public string Target { get; set; }
[XmlAttribute(AttributeName = "title")]
public string Title { get; set; }
[XmlAttribute(AttributeName = "querystring")]
public string Querystring { get; set; }
[XmlAttribute(AttributeName = "linktext")]
public string Linktext { get; set; }
}
[XmlRoot(ElementName = "links")]
public class Links
{
[XmlElement(ElementName = "link")]
public List<Link> Link { get; set; }
}
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);
When I deserialize the XML below, from a third-party, my objects are always null.
XML
<?xml version="1.0"?>
<OrderImport xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Reply i:nil="true">
</Reply>
<ReplyStatus i:nil="true">
<DebugInfo>
</DebugInfo>
<PerformanceLogInfo>
</PerformanceLogInfo>
</ReplyStatus>
<Reply>
<OrderNumber>4063286</OrderNumber>
</Reply>
<ReplyStatus>
<Result>0</Result>
<Message>
</Message>
</ReplyStatus>
</OrderImport>
C# Class
[XmlRoot(ElementName = "OrderImport")]
public class OrderImport
{
[XmlElement(ElementName = "Reply")]
public List<Reply> Reply { get; set; }
[XmlElement(ElementName = "ReplyStatus")]
public List<ReplyStatus> ReplyStatus { get; set; }
[XmlAttribute(AttributeName = "i", Namespace = "http://www.w3.org/2000/xmlns/")]
public string I { get; set; }
}
[XmlRoot(ElementName= "Reply")]
public class Reply
{
[XmlAttribute(AttributeName = "nil", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
public string Nil { get; set; }
[XmlElement(ElementName = "OrderNumber")]
public string OrderNumber { get; set; }
}
[XmlRoot(ElementName = "ReplyStatus")]
public class ReplyStatus
{
[XmlElement(ElementName = "DebugInfo")]
public string DebugInfo { get; set; }
[XmlElement(ElementName = "PerformanceLogInfo")]
public string PerformanceLogInfo { get; set; }
[XmlAttribute(AttributeName = "nil", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
public string Nil { get; set; }
[XmlElement(ElementName = "Result")]
public string Result { get; set; }
[XmlElement(ElementName = "Message")]
public string Message { get; set; }
}
I believe the problem has to do with the first occurrence of the objects Reply and ReplyStatus being null.
I'm trying to deserialize like so
httpResponseMessage.Content.ReadAsAsync<OrderImport>().Result;
However, I've found that if I deserialize like this it works just fine
stringres = httpResponseMessage.Content.ReadAsStringAsync().Result;
using (var stringreader = new StringReader(stringres))
{
var result = (OrderImport)xmlSerializer.Deserialize(stringreader);
}
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; }
}
I am attempting to read data from an XML file in C# (for Windows Phone).
I return the following XML file:
private async void GetCoords2()
{
string requestURI = "https://maps.googleapis.com/maps/api/geocode/xml?address=Donegal%20Town&key=XXX";
HttpWebRequest request = HttpWebRequest.Create(requestURI) as HttpWebRequest;
WebResponse response = await request.GetResponseAsync();
using (var reader = new StreamReader(response.GetResponseStream()))
{
responseContent = reader.ReadToEnd();
// Do anything with you content. Convert it to xml, json or anything.
ParseContent();
}
}
I am attempting to retrieve the first instance of latitude and longtitude from the XML file, which is available here: https://maps.googleapis.com/maps/api/geocode/xml?address=Donegal%20Town&key=XXX
I have followed several samples from online, and previous projects I have worked on, but none seem to be working.
How can I retrieve the first instance of lat and lon?
Thanks.
Edit: had to remove key from URL, posted screenshot of image instead.
UPDATE: The code I currently have.
void ParseContent()
{
XmlReader xmlReader = XmlReader.Create(responseContent);
List<string> aTitle = new List<string>();
// Add as many as attributes you have in your "stop" element
XmlReader reader = XmlReader.Create(responseContent);
reader.ReadToDescendant("location");
while (reader.Read())
{
reader.MoveToFirstAttribute();
reader.ReadToFollowing("lat");
string latX = reader.ReadElementContentAsString();
reader.ReadToFollowing("lng");
string lngX = reader.ReadElementContentAsString();
//reader.ReadToFollowing("Subcategory");
//string subcategory = reader.ReadElementContentAsString();
//reader.ReadToFollowing("Favourited");
//Boolean favourited = Boolean.Parse(reader.ReadElementContentAsString());
//basketxml.Add(new Pets(name, category, subcategory, description, dob, stock, price, image, id, favourited));
MessageBox.Show(latX + " / " + lngX);
}
}
FOUND ANSWER HERE:
http://www.superstarcoders.com/blogs/posts/geocoding-in-c-sharp-using-google-maps.aspx
Try something like this....
Usings...
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
Classes.... .(created from your XML using http://xmltocsharp.azurewebsites.net/)
[XmlRoot(ElementName = "address_component")]
public class Address_component
{
[XmlElement(ElementName = "long_name")]
public string Long_name { get; set; }
[XmlElement(ElementName = "short_name")]
public string Short_name { get; set; }
[XmlElement(ElementName = "type")]
public List<string> Type { get; set; }
}
[XmlRoot(ElementName = "location")]
public class Location
{
[XmlElement(ElementName = "lat")]
public string Lat { get; set; }
[XmlElement(ElementName = "lng")]
public string Lng { get; set; }
}
[XmlRoot(ElementName = "southwest")]
public class Southwest
{
[XmlElement(ElementName = "lat")]
public string Lat { get; set; }
[XmlElement(ElementName = "lng")]
public string Lng { get; set; }
}
[XmlRoot(ElementName = "northeast")]
public class Northeast
{
[XmlElement(ElementName = "lat")]
public string Lat { get; set; }
[XmlElement(ElementName = "lng")]
public string Lng { get; set; }
}
[XmlRoot(ElementName = "viewport")]
public class Viewport
{
[XmlElement(ElementName = "southwest")]
public Southwest Southwest { get; set; }
[XmlElement(ElementName = "northeast")]
public Northeast Northeast { get; set; }
}
[XmlRoot(ElementName = "geometry")]
public class Geometry
{
[XmlElement(ElementName = "location")]
public Location Location { get; set; }
[XmlElement(ElementName = "location_type")]
public string Location_type { get; set; }
[XmlElement(ElementName = "viewport")]
public Viewport Viewport { get; set; }
[XmlElement(ElementName = "bounds")]
public Bounds Bounds { get; set; }
}
[XmlRoot(ElementName = "result")]
public class Result
{
[XmlElement(ElementName = "type")]
public List<string> Type { get; set; }
[XmlElement(ElementName = "formatted_address")]
public string Formatted_address { get; set; }
[XmlElement(ElementName = "address_component")]
public List<Address_component> Address_component { get; set; }
[XmlElement(ElementName = "geometry")]
public Geometry Geometry { get; set; }
[XmlElement(ElementName = "place_id")]
public string Place_id { get; set; }
}
[XmlRoot(ElementName = "bounds")]
public class Bounds
{
[XmlElement(ElementName = "southwest")]
public Southwest Southwest { get; set; }
[XmlElement(ElementName = "northeast")]
public Northeast Northeast { get; set; }
}
[XmlRoot(ElementName = "GeocodeResponse")]
public class GeocodeResponse
{
[XmlElement(ElementName = "status")]
public string Status { get; set; }
[XmlElement(ElementName = "result")]
public List<Result> Result { get; set; }
}
Code...
try
{
string query1 = string.Format("https://maps.googleapis.com/maps/api/geocode/xml?address=Donegal%20Town&key=<Your Key>");
XmlDocument GeocodeResponse = new XmlDocument();
GeocodeResponse.Load(query1);
string XMLGeocodeResponse = GeocodeResponse.InnerXml.ToString();
byte[] BUFGeocodeResponse = ASCIIEncoding.UTF8.GetBytes(XMLGeocodeResponse);
MemoryStream ms1 = new MemoryStream(BUFGeocodeResponse);
XmlSerializer DeserializerPlaces = new XmlSerializer(typeof(GeocodeResponse), new XmlRootAttribute("GeocodeResponse"));
using (XmlReader reader = new XmlTextReader(ms1))
{
GeocodeResponse dezerializedXML = (GeocodeResponse)DeserializerPlaces.Deserialize(reader);
Location LatLng = dezerializedXML.Result[0].Geometry.Location;
}// Put a break-point here, then mouse-over LatLng and you should have you values
}
catch (System.Exception)
{
throw;
}
This will deserialize the whole thing into a single object, then you can select elements you need (as you can see with 'LatLng' above has the two coordinates you wanted to extract)...