Deserialise XML response from server

那年仲夏 提交于 2019-12-11 22:04:54

问题


I want to deserialise an object. I saw the following code in msdn.com:

private void DeserializeObject(string filename)
    {
    Debug.WriteLine("Reading with XmlReader");

    // Create an instance of the XmlSerializer specifying type and namespace.
    XmlSerializer serializer = new XmlSerializer(typeof(User));

    // A FileStream is needed to read the XML document.
    FileStream fs = new FileStream(filename, FileMode.Open);
    XmlReader reader = XmlReader.Create(filename);

    // Declare an object variable of the type to be deserialized.
    User i;

    // Use the Deserialize method to restore the object's state.
    i = (User)serializer.Deserialize(reader);
    fs.Close();

    // Write out the properties of the object.
    Debug.WriteLine(
    i.field1+ "\t" +
    i.field2+ "\t" +
    i.field3+ "\t" +
    i.field4);
    }

However, I don't want to deserialise a file, but rather an XML stream I get from the server as a response, corresponding code shown here:

HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
            HttpWebResponse response;
            response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);

            Stream streamResponse = response.GetResponseStream();
            StreamReader streamReader = new StreamReader(streamResponse);
            var Response = streamReader.ReadToEnd();
            streamResponse.Close();
            streamReader.Close();
            response.Close();
            if (Response == "")
            {
                //show some error msg to the user        
            }
            else
            {
                //Your response will be available in "Response" 
                string mystring = Response.ToString();

                //Mytext.Text = mystring;
                Debug.WriteLine(mystring);
                DeserializeObject("myxml");  <---- call deserialise 
}

How can I achieve this? I created a class called "User" according to XML by using the xsd.exe tool.


回答1:


OK I did it. This is how :-

private void DeserializeObject(string inxml)
    {
        Debug.WriteLine("Reading with XmlReader");
        var xml = inxml;
        var serializer = new XmlSerializer(typeof(User));
        using (var reader = new StringReader(xml))
        {
            var user = (User)serializer.Deserialize(reader);
            Debug.WriteLine(
                            user.Number + "\t" +
                            user.Id + "\t" +
                            user.TextKey + "\t" +
                            user.Agent );
        }
    }

Instead of passing the file url, I passed the complete string. And the rest is as shown above.

Hope this will be helpful to someone who is learning.



来源:https://stackoverflow.com/questions/18105126/deserialise-xml-response-from-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!