昨天我确实询问过如何在Windows Phone 7上使用Web服务从一个复杂的xml文件中提取一些数据,但不幸的是我没有得到答案,而且我仍然卡住了。 这是我编写的c#代码,并没有在我的应用程序屏幕上显示数据:
public MainPage()
{
InitializeComponent();
SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;
Uri url = new Uri("http://www.google.com/ig/api?weather=paris", UriKind.Absolute);
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(url);
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
ListBoxItem areaItem = null;
StringReader stream = new StringReader(e.Result);
XmlReader reader = XmlReader.Create(stream);
string day = String.Empty;
string areaName = String.Empty;
string low = String.Empty;
string high = String.Empty;
string condition = String.Empty;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case ("day_of_week"):
{
if (true == reader.MoveToFirstAttribute())
{
reader.MoveToContent();
day = reader.ReadElementContentAsString();
day = reader.Value.ToString();
areaItem = new ListBoxItem();
areaItem.Content = day;
listBox1.Items.Add(areaItem);
}
} break;
case ("low"):
{
if (true == reader.MoveToFirstAttribute())
{
reader.MoveToContent();
low = reader.ReadElementContentAsString();
low = reader.Value.ToString();
areaItem = new ListBoxItem();
areaItem.Content = low;
listBox1.Items.Add(areaItem);
}
} break;
case ("high"):
{
if (true == reader.MoveToFirstAttribute())
{
reader.MoveToContent();
high = reader.ReadElementContentAsString();
high = reader.Value.ToString();
areaItem = new ListBoxItem();
areaItem.Content = high;
listBox1.Items.Add(areaItem);
}
} break;
case ("condition"):
{
if (true == reader.MoveToFirstAttribute())
{
reader.MoveToContent();
condition = reader.ReadElementContentAsString();
condition = reader.Value.ToString();
areaItem = new ListBoxItem();
areaItem.Content = condition;
listBox1.Items.Add(areaItem);
}
} break;
}
}
}
}
}
}
}
答案 0 :(得分:0)
你过于复杂,一切都很简单,使用
public class ForecastItem
{
public string a {get; set;}
public string b {get; set;}
}
等等
private void forecastReader_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs dc)
{
if (dc.Error != null)
{
return;
}
XElement xmlNews = XElement.Parse(dc.Result);
listBox1.ItemsSource = from item in xmlNews.Descendants("parent").Elements("sub")
select new ForecastItem
{
a = item.Element("node").Value,
b = item.Element("title").Value,
};
}
您从这里开始做的就是将数据绑定到您的XAML数据模板