Reputation: 11340
I am currently working on some functionality that makes an httppost then get a response.
Here's the code I'm currently working with:
public string SubmitRequest(string postUrl, string contentType, string postValues)
{
var req = WebRequest.Create(postUrl);
req.Method = "POST";
req.ContentType = contentType;
try
{
using (var reqStream = req.GetRequestStream())
{
var writer = new StreamWriter(reqStream);
writer.WriteLine(postValues);
}
var resp = req.GetResponse();
using (var respStream = resp.GetResponseStream())
{
var reader = new StreamReader(respStream);
return reader.ReadToEnd().Trim();
}
}
catch(WebException ex)
{
// do something here
}
return string.Empty;
}
The function returns xml in string format, for instance:
<result>
<code>Failed</code>
<message>Duplicate Application</message>
</result>
This needs to be converted into a class object - but i'm not sure how to go about it in the correct way.
Any advice appreciated.
Upvotes: 2
Views: 16036
Reputation: 931
You want to deserialize the returned xml into an object. This is a basic example:
//m is the string based xml representation of your object. Make sure there's something there
if (!string.IsNullOrWhiteSpace(m))
{
//Make a new XMLSerializer for the type of object being created
var ser = new XmlSerializer(typeof(yourtype));
//Deserialize and cast to your type of object
var obj = (yourtype)ser.Deserialize(new StringReader(m));
return obj ;
}
Upvotes: 3