WP7从xml Web服务返回最近7天的数据

时间:2011-01-10 03:17:02

标签: xml linq web-services windows-phone-7

我正在尝试从xml Web服务返回最近7天的数据,但没有运气。有人可以解释一下我将如何实现这一目标吗? XML如下:

<node>
    <api>
        <usagelist>
            <usage day="2011-01-01">
                <traffic name="total" unit="bytes">23579797</traffic> 
            </usage>
            <usage day="2011-01-02">
                <traffic name="total" unit="bytes">23579797</traffic> 
            </usage>
            <usage day="2011-01-03">
                <traffic name="total" unit="bytes">23579797</traffic> 
            </usage>
            <usage day="2011-01-04">
                <traffic name="total" unit="bytes">23579797</traffic> 
            </usage>
        </usagelist>
    </api>
</node>

修改

我想要检索的数据将用于填充折线图。具体而言,我需要过去7天的day属性值和流量元素值。目前,我已经有了以下代码,不过它只显示第一天7次,第一天流量为7次。

XDocument xDocument = XDocument.Parse(e.Result);

        var values = from query in xDocument.Descendants("usagelist")
                   select new History
                   {
                       day = query.Element("usage").Attribute("day").Value,
                       traffic = query.Element("usage").Element("traffic").Value
                   };

        foreach (History history in values)
        {
            ObservableCollection<LineGraphItem> Data = new ObservableCollection<LineGraphItem>()
            {
                new LineGraphItem() { yyyymmdd = history.day, value = double.Parse(history.traffic) },
                new LineGraphItem() { yyyymmdd = history.day, value = double.Parse(history.traffic) },
                new LineGraphItem() { yyyymmdd = history.day, value = double.Parse(history.traffic) },
                new LineGraphItem() { yyyymmdd = history.day, value = double.Parse(history.traffic) },
                new LineGraphItem() { yyyymmdd = history.day, value = double.Parse(history.traffic) },
                new LineGraphItem() { yyyymmdd = history.day, value = double.Parse(history.traffic) },
                new LineGraphItem() { yyyymmdd = history.day, value = double.Parse(history.traffic) },
            };

            lineGraph1.DataSource = Data;
        }

1 个答案:

答案 0 :(得分:2)

这将为您提供一个列表,其中包含基于您的XML的过去7天内DateTraffic属性的元素:

var trafficList = xmlDoc.Descendants("usage")
                        .Where(d => (DateTime.Now.Date - DateTime.Parse(d.Attribute("day").Value).Date) <= TimeSpan.FromDays(7))
                        .Select(d => new 
                                { Day = d.Attribute("day").Value, 
                                  Traffic = d.Descendants("traffic").First().Value 
                                })
                        .ToList();

现在您拥有了数据,您可以创建新的集合并逐个添加流量数据:

ObservableCollection<LineGraphItem> Data = new ObservableCollection<LineGraphItem>();
foreach (var history in trafficList)
    Data.Add(new LineGraphItem() { yyyymmdd = history.Day, value = double.Parse(history.Traffic) });