如何解析Post方法响应中的xml字符串?

时间:2011-08-17 09:09:54

标签: data-binding windows-phone-7 xml-parsing

我有一个从Post方法返回的xml字符串:

private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
    HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

    // End the operation
    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
    HttpStatusCode rcode = response.StatusCode;

    var stream = new GZipInputStream(response.GetResponseStream());
    using (StreamReader reader = new StreamReader(stream))
    {
        responseString = reader.ReadToEnd();                
    }          

    response.Close();
}

responseString是我要解析的字符串,使用下面的parseXmlString类。但是由于静态,我不能直接调用方法parseXmlString。如何将responseString传递给parseXmlString方法以使它们解析并绑定到listBox。或者无论如何都会有相同的结果。

void parseXmlString()
{
    byte[] byteArray = Encoding.UTF8.GetBytes(responseString);
    MemoryStream str = new MemoryStream(byteArray);
    str.Position = 0;

    XDocument xdoc = XDocument.Load(str);

    var data = from query in xdoc.Descendants("tracks").Elements("item")
               select new searchResult
               {
                   artist = (string)query.Element("artist"),
                   album = (string)query.Element("album"),
                   track = (string)query.Element("track"),
                   //   artistA = (string)query.Element("artists").Element("artist"),
               };
    //  ListBox lb = new ListBox();

    listBox1.ItemsSource = data;

    var data1 = from query in xdoc.Descendants("artists").Elements("item")
                select new searchResult
                {
                    artistA = (string)query.Element("artist"),
                };
    listBox2.ItemsSource = data1;
}

1 个答案:

答案 0 :(得分:1)

你的方法是颠倒的逻辑。你知道你可以在方法上有返回值,对吗? - )

您需要做的是让ParseXmlString方法将responseString作为参数,让它返回创建的IEnumerable,如下所示:

private IEnumerable<SearchResult> ParseXmlString(responseString)
{
    XDocument xdoc = XDocument.Load(responseString);

    var data =
        from query in xdoc.Descendants("tracks").Elements("item")
        select new SearchResult
        {
           Artist = (string)query.Element("artist"),
           Album = (string)query.Element("album"),
           Track = (string)query.Element("track"),
        };

    return
        from query in xdoc.Descendants("artists").Elements("item")
        select new SearchResult
        {
           ArtistA = (string)query.Element("artist"),
        };
}

更改异步代码处理,在读完responseString时执行对UI线程的回调。 然后,在您的UI线程上,您将执行:

// This being your method to get the async response
GetResponseAsync(..., responseString =>
{
    var searchResults = ParseXmlString(responseString);
    listBox2.ItemsSource = searchResults;
})

如果您需要对回调有一些基本的了解,可以看到这个答案:Callbacks in C#