从服务器反序列化XML响应

时间:2013-08-07 13:45:41

标签: xml windows-phone-7 deserialization xsd.exe

我想反序列化一个对象。我在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);
    }

但是,我不想反序列化文件,而是我从服务器获取的XML流作为响应,相应的代码如下所示:

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 
}

我怎样才能做到这一点?我使用xsd.exe工具根据XML创建了一个名为“User”的类。

1 个答案:

答案 0 :(得分:0)

好的,我做到了。 这是如何: -

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 );
        }
    }

我没有传递文件网址,而是传递了完整的字符串。其余的如上所示。

希望这对正在学习的人有所帮助。