2

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.

dotnetnoob
  • 10,783
  • 20
  • 57
  • 103
  • do you know what kind of responses you can get? I mean which nodes can be present in the response – ppetrov May 04 '13 at 16:54
  • 1
    Take a good look at this SO post: http://stackoverflow.com/questions/10518372/how-to-deserialize-xml-to-object Hope that helps. – David Tansey May 04 '13 at 17:12

1 Answers1

3

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 ;
    }
Matt
  • 931
  • 5
  • 13