Saturday, 18 April 2015

How to parse XML response using HttpClient in .Net 4.0 to .Net Class?



I have a web service that return xml in response.


Below is a screenshot of he xml response :



<?xml version="1.0" encoding="utf-8"?>
<Root>
<Header>
<Message type="String"></Message>
</Header>
<Output>
<Rows>
<Row>
<Result type="Integer">1021806</Result>
</Row>
</Rows>
</Output>
</Root>


Here is my .net Model that represent the xml response :



public class ResponseModel
{
public class Root
{
public Header header { get; set; }
public Output output { get; set; }
}
public class Header
{
public string Message { get; set; }
}
public class Output
{
public List<Row> Rows { get; set; }
}
public class Row
{
public int Result { get; set; }
}
}


I am using HttpClient Class to send the request the specified web service.


Here is my code :



using (var client = new System.Net.Http.HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/xml"));
var response = client.GetAsync("myWebServiceUrl").Result;
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content;
}
}


responseContent has three methods :


ReadAsStringAsync()


ReadAsStreamAsync()


ReadAsByteArrayAsync()


What are the differences between the three methods ?


Which one Should I use for xml response and how to parse the xml to the required ResponseModel ?


Any help is appreciated.


Thanks.


No comments:

Post a Comment