Patrick Patrick - 11 months ago 45
C# Question

Working With Web Response Stream and De-serialization into C# object

I have 2 specific questions with regards to passing a

(from a method) and deserialization into object (another method).

XML Response I get from a
(please note there are no root tags)

<?xml version="1.0" encoding="UTF-8"?>
<response id="-2d953936:14174bb0cf3:-5213">
<date>2013-10-01 12:01:55.532999</date>
<message>Market is open</message>

Method 1 - ResponseMethod - Currently returning string

private static string GetResponse(HttpWebRequest request)
var v_Response = request.GetResponse();
var v_DataStream = v_Response.GetResponseStream();

var v_Reader = new System.IO.StreamReader(v_DataStream);
var x_XMLResponse = v_Reader.ReadToEnd();

//Close all Stream logic
v_Reader.Close(); v_DataStream.Close(); v_Response.Close();

return x_XMLResponse;

Method 2 - Convert the XML to an object

// I would use XDocument and Lin2XML to get my typed object - for example MarketStatus

Questions are:

  1. I am currently passing string from Method 1. That doesnt help me in deserializing from XML to object. Should I be passing the return value as
    and then use that as an input into method 2 to get my typed object. Is that a standard approach or there are better ways to this?

  2. My ultimate objective is that the return value from second method should be an object.

Additional Note:

  1. The reason this functionality is broken into 2 methods because I want the web response method and deserailization separate for testing purposes.

  2. I don't have an XSD but have created a

Any code snippets/suggestions will really appreciate

Answer Source

We typically use a generic method, similar to the following (simplified for posting), which uses the XMLSerializer to deserialize an XML string representation into the corresponding object.

    public T ReturnObjectfromXml<T>(string xmlForm)
        XmlSerializer xs = new XmlSerializer(typeof(T));
        StringReader sr = new StringReader(xmlForm);
        XmlTextReader xts = new XmlTextReader(sr);
        return ((T)xs.Deserialize(xts));

Hope this helps.