转载

Windows 10开发基础——XML和JSON (二)

主要内容:

  • Linq to XML
  • Newtonsoft.Json.Linq来解析JSON
  • 博客园RSS(http://www.cnblogs.com/rss)的解析
  • UWP调用自己实现的Web API

1.Linq to XML

     Linq to XML不是一个新鲜的话题了,网上以及各种资料对这个介绍都比较多。今天就简单了解下,不做深入的研究。。。在代码中生成XML文档,使用Linq to XML会比Windows.Data.Xml.Dom命名空间下的类简单,使用起来也更加灵活。Linq to XML是对Linq表达式的扩展,我们也可以在处理XML时用上Linq语句。

先直接上一段代码:

XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", null));   XElement root = new XElement("students",    new XElement("student", new XAttribute("id", "201313138063"), new XAttribute("name", "czh"), new XAttribute("age", 18)),    new XElement("student", new XAttribute("id", "201313138064"), new XAttribute("name", "dyq"), new XAttribute("age", 19)),    new XElement("student", new XAttribute("id", "201313138065"), new XAttribute("name", "wxk"), new XAttribute("age", 22)),    new XElement("student", new XAttribute("id", "201313138069"), new XAttribute("name", "cmf"), new XAttribute("age", 20)));   xdoc.Add(root); textBlock.Text= xdoc.ToString(); 

首先我们创建了一个XDocument对象,代表整个XML文档,在创建这个对象时,我们传入了一个XDeclaration对象,这个对象声明了xml的基本信息(<?xml version="1.0" encoding="utf-8"?>)。XElement对象则对应着一个个的XML标签元素,XAttribute则对应这些元素里的属性。这段代码里面,root对应着<studens>标签,然后创建root时,我们传入了多个XElement对象,这些对象对应着<students>里面的<student>标签,然后把root添加到xdoc中,这样一个XML文档就创建完成了。对比上面的代码和下面生成的XML看一下咯。

<?xml version="1.0"?> <students>    <student age="18" name="czh" id="201313138063"/>    <student age="19" name="dyq" id="201313138064"/>    <student age="22" name="wxk" id="201313138065"/>    <student age="20" name="cmf" id="201313138069"/> </students>

接着,我们把上面的XML转化为对象列表,用列表控件进行显示:

XDocument xdoc = XDocument.Parse(textBlock.Text);     XElement root= xdoc.Root;     var students = from student in root.Elements("student")                            select new                            {                                SId=(string)student.Attribute("id"),                                SName= (string)student.Attribute("name"),                               SAge = (int)student.Attribute("age")                            };     listView.ItemsSource = students;

在这里我们用到了Linq中的select语句,将root(对应于students)中的所有student元素转换成了匿名对象,这个匿名对象有SId、SName、SAge三个属性,然后将这些匿名对象组成的students(类型为IEnumerable<T>)绑定到ListView控件上显示:

Windows 10开发基础——XML和JSON (二)

2.Newtonsoft.Json.Linq来解析JSON

     Newtonsoft.Json.Linq是一个比较火的第三方JSON解析库,我们来简单使用下。。。在建好的项目上右击“引用”节点,选择“管理Nuget包”,然后在搜索栏里面输入“Newtonsoft”,选择第一个,点安装就是了。我们要解析JSON数据来源于 中国和世界天气全能版 (http://apistore.baidu.com/apiworks/servicedetail/478.html)

这个第三方库使用起来还是比较方便的,我们主要用到了JObject、JToken、JArray三个类,直接贴代码。

前台xaml:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">   <Grid.RowDefinitions>    <RowDefinition Height="50"></RowDefinition>    <RowDefinition></RowDefinition>    <RowDefinition></RowDefinition>    <RowDefinition></RowDefinition>   </Grid.RowDefinitions>   <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">    <TextBox x:Name="tbCity"  Margin="10,10,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="235"/>    <Button x:Name="btnSearch" Content="Search" HorizontalAlignment="Center" Margin="20,10,0,0" VerticalAlignment="Top" Click="btnSearch_Click"/>   </StackPanel>   <Grid Visibility="Collapsed" HorizontalAlignment="Center" Grid.Row="1" x:Name="now_grid">    <Grid.RowDefinitions>     <RowDefinition></RowDefinition>     <RowDefinition></RowDefinition>     <RowDefinition></RowDefinition>     <RowDefinition></RowDefinition>     <RowDefinition></RowDefinition>     <RowDefinition></RowDefinition>     <RowDefinition></RowDefinition>     <RowDefinition></RowDefinition>     <RowDefinition></RowDefinition>    </Grid.RowDefinitions>    <Grid.ColumnDefinitions>     <ColumnDefinition></ColumnDefinition>     <ColumnDefinition></ColumnDefinition>    </Grid.ColumnDefinitions>    <TextBlock Grid.Row="0" VerticalAlignment="Center" HorizontalAlignment="Center" Grid.Column="0" Text="当前天气状况"></TextBlock>    <TextBlock Grid.Row="1"  VerticalAlignment="Center" HorizontalAlignment="Center"  Grid.Column="0" Text="当前温度(C)"></TextBlock>    <TextBlock Grid.Row="2" VerticalAlignment="Center" HorizontalAlignment="Center"  Grid.Column="0" Text="相对湿度(%)"></TextBlock>    <TextBlock Grid.Row="3" VerticalAlignment="Center" HorizontalAlignment="Center"  Grid.Column="0" Text="能见度(km)"></TextBlock>    <TextBlock Grid.Row="4" VerticalAlignment="Center" HorizontalAlignment="Center"  Grid.Column="0" Text="空气质量指数"></TextBlock>    <TextBlock Grid.Row="5" VerticalAlignment="Center" HorizontalAlignment="Center"  Grid.Column="0" Text="PM2.5(ug/m³)"></TextBlock>    <TextBlock Grid.Row="6" VerticalAlignment="Center" HorizontalAlignment="Center"  Grid.Column="0" Text="空气质量类别"></TextBlock>    <TextBlock Grid.Row="7" VerticalAlignment="Center" HorizontalAlignment="Center"  Grid.Column="0" Text="风向"></TextBlock>    <TextBlock Grid.Row="8" VerticalAlignment="Center" HorizontalAlignment="Center"  Grid.Column="0" Text="风力"></TextBlock>    <TextBlock Margin="12,0,0,0" Grid.Row="0" Grid.Column="1" Text="{Binding Txt}"></TextBlock>    <TextBlock Margin="12,0,0,0" Grid.Row="1" Grid.Column="1" Text="{Binding Tmp}"></TextBlock>    <TextBlock Margin="12,0,0,0" Grid.Row="2" Grid.Column="1" Text="{Binding Hum}"></TextBlock>    <TextBlock Margin="12,0,0,0" Grid.Row="3" Grid.Column="1" Text="{Binding Vis}"></TextBlock>    <TextBlock Margin="12,0,0,0" Grid.Row="4" Grid.Column="1" Text="{Binding Aqi}"></TextBlock>    <TextBlock Margin="12,0,0,0" Grid.Row="5" Grid.Column="1" Text="{Binding Pm25}"></TextBlock>    <TextBlock Margin="12,0,0,0" Grid.Row="6" Grid.Column="1" Text="{Binding Qlty}"></TextBlock>    <TextBlock Margin="12,0,0,0" Grid.Row="7" Grid.Column="1" Text="{Binding Winddir}"></TextBlock>    <TextBlock Margin="12,0,0,0" Grid.Row="8" Grid.Column="1" Text="{Binding Windsc}"></TextBlock>   </Grid>   <FlipView Visibility="Collapsed" x:Name="fv" Grid.Row="2">    <FlipView.ItemTemplate>     <DataTemplate>      <Grid>       <Grid.RowDefinitions>        <RowDefinition Height="2*"></RowDefinition>        <RowDefinition Height="5*"></RowDefinition>        <RowDefinition Height="2*"></RowDefinition>       </Grid.RowDefinitions>       <StackPanel Orientation="Vertical">        <TextBlock Text="{Binding Date}" HorizontalAlignment="Center"></TextBlock>        <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">         <TextBlock Margin="48,0,0,0" Text="日出时间:"></TextBlock>         <TextBlock  Margin="12,0,0,0" Text="{Binding Astrosr}"></TextBlock>         <TextBlock Margin="24,0,0,0" Text="日出时间:"></TextBlock>         <TextBlock  Margin="12,0,0,0" Text="{Binding Astross}"></TextBlock>        </StackPanel>       </StackPanel>       <Grid Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center">        <Grid.RowDefinitions>         <RowDefinition></RowDefinition>         <RowDefinition></RowDefinition>         <RowDefinition></RowDefinition>         <RowDefinition></RowDefinition>        </Grid.RowDefinitions>        <Grid.ColumnDefinitions>         <ColumnDefinition></ColumnDefinition>         <ColumnDefinition></ColumnDefinition>        </Grid.ColumnDefinitions>        <TextBlock Grid.Row="0" VerticalAlignment="Center" HorizontalAlignment="Center" Grid.Column="0" Text="相对湿度(%)"></TextBlock>        <TextBlock Grid.Row="1"  VerticalAlignment="Center" HorizontalAlignment="Center"  Grid.Column="0" Text="降水概率"></TextBlock>        <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Hum}"></TextBlock>        <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Pop}"></TextBlock>        <StackPanel Orientation="Horizontal" Grid.Row="2" Grid.ColumnSpan="2">         <TextBlock  Margin="36,4,0,0"   Text="最高温度(C):"></TextBlock>         <TextBlock Margin="12,4,0,0" Text="{Binding Tmpmax}"></TextBlock>         <TextBlock Margin="24,4,0,0"   Text="最低温度(C):"></TextBlock>         <TextBlock Margin="12,4,0,0" Text="{Binding Tmpmin}"></TextBlock>        </StackPanel>        <StackPanel Orientation="Horizontal" Grid.Row="3" Grid.ColumnSpan="2">         <TextBlock  Margin="24,4,0,0"   Text="白天天气状况:"></TextBlock>         <TextBlock Margin="12,4,0,0" Text="{Binding Txt_d}"></TextBlock>         <TextBlock Margin="24,4,0,0"   Text="夜晚天气状况:"></TextBlock>         <TextBlock Margin="12,4,0,0" Text="{Binding Txt_n}"></TextBlock>        </StackPanel>       </Grid>       <StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">        <TextBlock Margin="48,0,0,0" Text="风向:"></TextBlock>        <TextBlock  Margin="12,0,0,0" Text="{Binding Winddir}"></TextBlock>        <TextBlock Margin="24,0,0,0" Text="风力:"></TextBlock>        <TextBlock  Margin="12,0,0,0" Text="{Binding Windsc}"></TextBlock>       </StackPanel>      </Grid>     </DataTemplate>    </FlipView.ItemTemplate>   </FlipView>   <Grid x:Name="sugestion_grid" Visibility="Collapsed" Grid.Row="3" Margin="12">    <Grid.RowDefinitions>     <RowDefinition Height="2*"></RowDefinition>     <RowDefinition Height="2*"></RowDefinition>    </Grid.RowDefinitions>    <Grid.ColumnDefinitions>     <ColumnDefinition></ColumnDefinition>     <ColumnDefinition></ColumnDefinition>    </Grid.ColumnDefinitions>    <Grid Margin="8" Grid.Row="0" Grid.Column="0">     <Grid.RowDefinitions>      <RowDefinition Height="auto"></RowDefinition>      <RowDefinition Height="auto"></RowDefinition>      <RowDefinition Height="auto"></RowDefinition>     </Grid.RowDefinitions>     <TextBlock Text="舒适度指数:"></TextBlock>     <TextBlock Grid.Row="1" Text="{Binding Comfbrf}"></TextBlock>     <TextBlock Grid.Row="2" Text="{Binding Comftxt}" TextWrapping="Wrap"></TextBlock>    </Grid>    <Grid Margin="8" Grid.Row="0" Grid.Column="1">     <Grid.RowDefinitions>      <RowDefinition Height="auto"></RowDefinition>      <RowDefinition Height="auto"></RowDefinition>      <RowDefinition Height="auto"></RowDefinition>     </Grid.RowDefinitions>     <TextBlock Text="穿衣指数:"></TextBlock>     <TextBlock Grid.Row="1" Text="{Binding Drsgbrf}"></TextBlock>     <TextBlock Grid.Row="2" Text="{Binding Drsgtxt}" TextWrapping="Wrap"></TextBlock>    </Grid>    <Grid Margin="8" Grid.Row="1" Grid.Column="0">     <Grid.RowDefinitions>      <RowDefinition Height="auto"></RowDefinition>      <RowDefinition Height="auto"></RowDefinition>      <RowDefinition Height="auto"></RowDefinition>     </Grid.RowDefinitions>     <TextBlock Text="感冒指数:"></TextBlock>     <TextBlock Grid.Row="1" Text="{Binding Flubrf}"></TextBlock>     <TextBlock Grid.Row="2" Text="{Binding Flutxt}" TextWrapping="Wrap"></TextBlock>    </Grid>    <Grid Margin="8" Grid.Row="1" Grid.Column="1">     <Grid.RowDefinitions>      <RowDefinition Height="auto"></RowDefinition>      <RowDefinition Height="auto"></RowDefinition>      <RowDefinition Height="auto"></RowDefinition>     </Grid.RowDefinitions>     <TextBlock Text="运动指数:"></TextBlock>     <TextBlock Grid.Row="1" Text="{Binding Sportbrf}"></TextBlock>     <TextBlock Grid.Row="2" Text="{Binding Sporttxt}" TextWrapping="Wrap"></TextBlock>    </Grid>   </Grid>  </Grid> View Code 

后台代码:

private async void btnSearch_Click(object sender, RoutedEventArgs e) {  HttpClient httpClient = new HttpClient();  httpClient.DefaultRequestHeaders.Add("apikey", "你的apikey");  string url = "http://apis.baidu.com/heweather/pro/weather?city=" + tbCity.Text;  HttpResponseMessage response = await httpClient.GetAsync(new Uri(url));  response.EnsureSuccessStatusCode();  string result = await response.Content.ReadAsStringAsync();  DeserilizeJson(result); } private void DeserilizeJson(string result) {  JObject jsonobj = JObject.Parse(result);  JArray jsonarry = JArray.Parse(jsonobj["HeWeather data service 3.0"].ToString());  WeathernowData(jsonarry);  DailyforecastData(jsonarry);  SuggestionsData(jsonarry); } private void WeathernowData(JArray jsonarry) {  Weathernow now = new Weathernow();  JToken weather = jsonarry[0]["now"];  now.Txt = weather["cond"]["txt"].ToString();  now.Tmp = weather["tmp"].ToString();  now.Aqi = jsonarry[0]["aqi"]["city"]["aqi"].ToString();  now.Pm25 = jsonarry[0]["aqi"]["city"]["pm25"].ToString();  now.Qlty = jsonarry[0]["aqi"]["city"]["qlty"].ToString();  now.Hum = weather["hum"].ToString();  now.Vis= weather["vis"].ToString();  now.Winddir= weather["wind"]["dir"].ToString();  now.Windsc= weather["wind"]["sc"].ToString();  if (now_grid.Visibility == Visibility.Collapsed)   now_grid.Visibility = Visibility.Visible;  now_grid.DataContext = now; } private void DailyforecastData(JArray jsonarry) {  List<Dailyforecast> dailyList = new List<Dailyforecast>();  JArray daily_forecast =JArray.Parse( jsonarry[0]["daily_forecast"].ToString());  for (int i = 0; i < daily_forecast.Count; i++)  {   dailyList.Add(new Dailyforecast() {    Date = daily_forecast[i]["date"].ToString() ,    Astrosr=daily_forecast[1]["astro"]["sr"].ToString(),    Astross= daily_forecast[1]["astro"]["ss"].ToString(),    Hum = daily_forecast[i]["hum"].ToString(),    Pop= daily_forecast[i]["pop"].ToString(),    Tmpmax = daily_forecast[i]["tmp"]["max"].ToString(),    Tmpmin = daily_forecast[i]["tmp"]["min"].ToString(),    Txt_d = daily_forecast[i]["cond"]["txt_d"].ToString(),    Txt_n = daily_forecast[i]["cond"]["txt_n"].ToString(),    Winddir = daily_forecast[i]["wind"]["dir"].ToString(),    Windsc = daily_forecast[i]["wind"]["sc"].ToString()   });  }  if (fv.Visibility == Visibility.Collapsed)   fv.Visibility = Visibility.Visible;  fv.ItemsSource = dailyList; } private void SuggestionsData(JArray jsonarry) {  Suggestions suggestions = new Suggestions();  JToken suggestion = jsonarry[0]["suggestion"];  suggestions.Comfbrf = suggestion["comf"]["brf"].ToString();  suggestions.Comftxt = suggestion["comf"]["txt"].ToString();  suggestions.Drsgbrf = suggestion["drsg"]["brf"].ToString();  suggestions.Drsgtxt = suggestion["drsg"]["txt"].ToString();  suggestions.Flubrf = suggestion["flu"]["brf"].ToString();  suggestions.Flutxt = suggestion["flu"]["txt"].ToString();  suggestions.Sportbrf = suggestion["sport"]["brf"].ToString();  suggestions.Sporttxt = suggestion["sport"]["txt"].ToString();  if (sugestion_grid.Visibility == Visibility.Collapsed)   sugestion_grid.Visibility = Visibility.Visible;  sugestion_grid.DataContext = suggestions; } 

Weathernow.cs:

/*  "txt": "晴" //天气状况描述  "tmp": "32",  //温度  "hum": "20%",  //相对湿度(%)  "vis": "10",  //能见度(km)             "aqi": "30",  //空气质量指数  "pm25": "7",  //PM2.5 1小时平均值(ug/m³)  "qlty": "优",  //空气质量类别  "winddir": "北风",  //风向  "windsc": "3级",  //风力     */     public class Weathernow     {         public string Txt { get; set; }         public string Tmp { get; set; }         public string Hum { get; set; }         public string Vis { get; set; }         public string Aqi { get; set; }         public string Pm25 { get; set; }         public string Qlty { get; set; }         public string Winddir { get; set; }         public string Windsc { get; set; }     } View Code 

Suggestions.cs:

/*     //舒适度指数   "comfbrf": "较不舒适",  //简介   "comftxt": "白天天气多云,同时会感到有些热,不很舒适。" //详细描述     //穿衣指数         "drsgbrf": "炎热",         "drsgtxt": "天气炎热,建议着短衫、短裙、短裤、薄型T恤衫等清凉夏季服装。"     //感冒指数        "flubrf": "少发",        "flutxt": "各项气象条件适宜,发生感冒机率较低。但请避免长期处于空调房间中,以防感冒。"     //运动指数       "sportbrf": "较适宜",       "sporttxt": "天气较好,户外运动请注意防晒。推荐您进行室内运动。"     //紫外线指数       "uvbrf": "中等",       "uvtxt": "属中等强度紫外线辐射天气,外出时建议涂擦SPF高于15、PA+的防晒护肤品,戴帽子、太阳镜。"     */     public class Suggestions     {  public string Comfbrf { get; set; }  public string Comftxt { get; set; }  public string Drsgbrf { get; set; }  public string Drsgtxt { get; set; }  public string Flubrf { get; set; }  public string Flutxt { get; set; }  public string Sportbrf { get; set; }  public string Sporttxt { get; set; }     } View Code 

Dailyforecast.cs:

/*      "date": "2015-07-02",  //预报日期           "astrosr": "04:50",  //日出时间      "astross": "19:47" //日落时间      "txt_d": "晴",  //白天天气状况描述      "txt_n": "晴" //夜间天气状况描述       "hum": "14",  //相对湿度(%)       "pop": "0",  //降水概率       "tmpmax": "34",  //最高温度       "tmpmin": "18" //最低温度       "winddir": "东南风",  //风向       "windsc": "3-4",  //风力  */    public class Dailyforecast  {   public string Date { get; set; }   public string Astrosr { get; set; }   public string Astross { get; set;}   public string Txt_d { get; set; }   public string Txt_n { get; set; }   public string Hum { get; set; }   public string Pop { get; set; }   public string Tmpmax { get; set; }   public string Tmpmin { get; set; }   public string Winddir { get; set; }   public string Windsc { get; set; }  } View Code 

我们来看截取的这一段JSON数据:

Windows 10开发基础——XML和JSON (二)

JObject jsonobj = JObject.Parse(result);JArray jsonarry = JArray.Parse(jsonobj["HeWeather data service 3.0"].ToString());

JToken suggestion = jsonarry[0]["suggestion"];suggestions.Comfbrf = suggestion["comf"]["brf"].ToString();

借助上面几行代码就可以取到第三行的“较舒适”三个字了,像jsonarry[0]["suggestion"]["comf"]["brf"]这样来取相应的数据还是相当方便的,动手试试,不太难的。我这里之所以这么多代码,是为了要解析出很多的JSON数据。。。。来看运行结果:(废话:查询结果依次是当前天气,FilpView控件展示的未来十天天气,一些天气指数)

Windows 10开发基础——XML和JSON (二)

3.博客园RSS(http://www.cnblogs.com/rss)的解析

      在UWP里面,Windows.Web.Syndication命名空间对访问RSS源提供了比较好的支持,然而这次对博客园RSS的解析并没有采用这个命名空间下的类,而是直接解析XML文档来的。个人感觉在解析的时候还是遇到了一些坑的,里面貌似留了一些空格等东西,反正SelectNodes等的那个Xpath怎么写都不太对,最后直接用GetElementsByTagName了,此痛试过就知道。。。我们的HttpClient类采用的是Windows.Web.Http命名空间下的,XmlDocument则来自Windows.Data.Xml.Dom命名空间。还是像以前提到的,XML解析用好”快速监视“根据情况动态调整一下,不太难的。ok,直接贴代码,不做过多解释。

前台xaml:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">  <Grid.ColumnDefinitions>   <ColumnDefinition Width="*"></ColumnDefinition>   <ColumnDefinition Width="*"></ColumnDefinition>  </Grid.ColumnDefinitions>  <ListView x:Name="listview" ItemClick="listview_ItemClick" IsItemClickEnabled="True">   <ListView.ItemTemplate>    <DataTemplate>     <StackPanel Orientation="Vertical" Margin="10">      <TextBlock TextWrapping="Wrap" Text="{Binding Title}" FontSize="18"/>      <StackPanel Orientation="Horizontal">       <TextBlock Text="{Binding AuthorName}" FontSize="15"/>       <TextBlock Text="{Binding PublishedTime}" FontSize="15" Margin="30,0,10,0"/>      </StackPanel>     </StackPanel>    </DataTemplate>   </ListView.ItemTemplate>  </ListView>  <WebView x:Name="wv" Grid.Column="1"/> </Grid> 

后台代码:(废话:把InitData方法放在MainPage的构造函数里面调用)

private async void InitData() {  HttpClient httpClient = new HttpClient();  httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible;MSIE 10.0;Windows NT 6.2;WOW64;Trident/6.0)");  HttpResponseMessage response = await httpClient.GetAsync(new Uri("http://www.cnblogs.com/rss"));  response.EnsureSuccessStatusCode();  string result = await response.Content.ReadAsStringAsync();  List<Article> articlelist = new List<Article>();  XmlDocument xdoc = new XmlDocument();  xdoc.LoadXml(result);  IXmlNode xn = xdoc.ChildNodes.Item(1);  //  feed  XmlElement topxe = (XmlElement)xn;  XmlNodeList nodelist = topxe.GetElementsByTagName("entry");  foreach (IXmlNode node in nodelist)  {       XmlNodeList xeIdnodelist = ((XmlElement)node).GetElementsByTagName("id");   XmlNodeList xeTitlenodelist = ((XmlElement)node).GetElementsByTagName("title");   XmlNodeList xePublishednodelist = ((XmlElement)node).GetElementsByTagName("published");   XmlNodeList xecontentnodelist = ((XmlElement)node).GetElementsByTagName("content");   XmlNodeList xeAuthornodelist = ((XmlElement)node).GetElementsByTagName("author");   string id = xeIdnodelist.Item(0).InnerText;   string title = xeTitlenodelist.Item(0).InnerText.Split('-')[0];   string published = xePublishednodelist.Item(0).InnerText;   string content = xecontentnodelist.Item(0).InnerText;   string authorname = xeAuthornodelist.Item(0).ChildNodes.Item(1).InnerText;   articlelist.Add(new Article() { Id = id, Title = title, AuthorName = authorname, PublishedTime = published, Content = content });  }  listview.ItemsSource = articlelist; } private void listview_ItemClick(object sender, ItemClickEventArgs e) {  Article article = e.ClickedItem as Article;  wv.NavigateToString(article.Content); } 
   Article类:
public  class Article  {   public string Id { get; set; }   public string Title { get; set; }   public string AuthorName { get; set; }   public string PublishedTime { get; set; }   public string Content { get; set; }  } View Code 

运行结果:(废话:我们用ListView控件来显示文章的标题等信息,文章的内容由WebView控件来展示)

Windows 10开发基础——XML和JSON (二)

4.UWP调用自己实现的Web API

我们来利用ASP.NET Web API实现一个简单的API接口供UWP客户端来调用。由于本人的ASP.NET技术有限,所以这个API几乎是靠Visual Studio来自动生成,我们的数据采用Database First的方式来实现。

Firstly,新建一个ASP.NET Web应用程序,然后来到下图,为简单起见,选择“Empty”模板,然后选中“Web API”,点击“确定”,ok。

Windows 10开发基础——XML和JSON (二)

Secondly,右击项目的“Models”文件夹,依次,“添加”-->"新建项",在右边选择“数据”,然后选择“ADO.NET 实体数据模型”,名称处命名,点击“添加”,ok

Windows 10开发基础——XML和JSON (二)

然后我们来到下图,选择“来自数据库的Code First”,点击“下一步”

Windows 10开发基础——XML和JSON (二)

接着是下图

Windows 10开发基础——XML和JSON (二)

点击新建连接,出现下图,服务器名“.”表示本机,然后登陆到服务器,选择要连接的数据库,测试连接,连接成功,点击“确定“即可

然后是此图,我们这次只用到Books表,所有就只选中它了。点击“完成”之后,会在Models文件夹下面生成许多的文件,自行查看。。。

Windows 10开发基础——XML和JSON (二)

前面这些步骤说起来比较麻烦,也可能还没说清楚,由于我之前已经完成了编码,再记录的博客,也会漏掉一些内容,这些如果是自己操作熟了,会很简单的。数据还可以采用Code First等方式,,,,,不详述了。

Then,右击“Controllers文件夹”,点击添加控制器,如下图,点击“添加”

Windows 10开发基础——XML和JSON (二)

之后是这个,选择数据上下文类和模型类,然后再点击“添加”

点击添加,然后会在Controller文件夹下生成BooksController.cs类文件(图上的Books1Controller是因为我之前已完成编码,已经有了BooksController。。。。),我们打开BooksController类,会看到自动生成了很多的方法(模板的强大力量啊,用起来确实很方便,由于只是演示,就用模板了。。。),代码很多,这里就不贴了,里面的方法大多都对应一种HTTP请求的。

比如下面这个方法:

// GET: api/Books

public IQueryable<Books> GetBooks()

{

return db.Books;

}

我们生成并开始调试,然后浏览器会报错:HTTP Error 403.14 - Forbidden,这时候,我们只需要在那个地址后面加上api/Books就ok,根据不同的浏览器会返回json或xml数据,其他的方法则类似。至此API接口已全部完成。

最后就是客户端的调用了。分别采用了请求XML和JSON的方式,由于HTTP请求以及XML和JSON的解析,前面已经学习过,这里不再赘述,直接贴代码。

请求XML数据:

private async void InitDataXml() {  HttpClient httpClient = new HttpClient();  httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/xml"));  HttpResponseMessage response = await httpClient.GetAsync(new Uri("http://localhost:64339/api/books"));  response.EnsureSuccessStatusCode();  string result = await response.Content.ReadAsStringAsync();  List<Books> bookslist = new List<Books>();  XmlDocument xdoc = new XmlDocument();  xdoc.LoadXml(result);  IXmlNode xn = xdoc.ChildNodes.Item(0);    XmlElement topxe = (XmlElement)xn;  XmlNodeList nodelist = xn.ChildNodes;  foreach (IXmlNode node in nodelist)  {   XmlElement xe = (XmlElement)node;   XmlNodeList xenodelist = xe.ChildNodes;   bookslist.Add(new Books() {    book_Name =xenodelist.Item(3).InnerText,    book_Author = xenodelist.Item(0).InnerText,    book_Isbn = xenodelist.Item(2).InnerText,    book_cate =xenodelist.Item(7).InnerText,    book_Press = xenodelist.Item(4).InnerText,    book_Rressdate = xenodelist.Item(6).InnerText,    book_Remain = Convert.ToInt32(xenodelist.Item(5).InnerText)   });  }  listView.ItemsSource = bookslist; } 

请求JSON数据:

private async void InitDataJson() {  HttpClient httpClient = new HttpClient();  httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/json"));  HttpResponseMessage response = await httpClient.GetAsync(new Uri("http://localhost:64339/api/books"));  response.EnsureSuccessStatusCode();  string result = await response.Content.ReadAsStringAsync();  List<Books> bookslist = new List<Books>();  JsonArray arrays = JsonArray.Parse(result);  for (int i = 0; i < arrays.Count; i++)  {   JsonObject obj = arrays.GetObjectAt((uint)i);   bookslist.Add(new Books() {    book_Name =obj.GetNamedString("book_Name"),    book_Author = obj.GetNamedString("book_Author"),    book_Isbn = obj.GetNamedString("book_Isbn"),    book_cate =obj.GetNamedString("book_cate"),    book_Press = obj.GetNamedString("book_Press"),    book_Rressdate = obj.GetNamedString("book_Rressdate"),    book_Remain = Convert.ToInt32(obj.GetNamedNumber("book_Remain"))   });  }  listView.ItemsSource = bookslist; } 

Book.cs:

public class Books  {   public int book_Id { get; set; }   public string book_Name { get; set; }   public string book_Author { get; set; }   public string book_Isbn { get; set; }   public string book_cate { get; set; }   public string book_Press { get; set; }   public string book_Rressdate { get; set; }   public int book_Remain { get; set; }  } View Code 

运行结果:

Windows 10开发基础——XML和JSON (二)

借助于ASP.NET Web API,我们最终将SQL Server数据库中的数据通过UWP应用进行了展示。(我发现最后的这个图表示的意思有点不够,懒得换了,懒)

好了,这就是本次的全部内容了,貌似有点乱,要Demo的留邮箱。太晚了,睡觉了,晚安!

正文到此结束
Loading...