WinRT知识积累1之读xml数据

前述:这个知识是在Windows8.1或WP8.1中运用Linq to xml获取一个xml文件里的数据。(网上也很多类似的知识,可以借鉴参考)

平台:windows8.1 metro 或者WP8.1

步骤:1、在项目中准备一个xml文件。我在项目中建立了一个city.xml,如图:

city.xml具体代码如下:

<?xml version="1.0" encoding="utf-8" ?>
<China>
  <city>
    <id>1</id>
    <name>北京</name>
    <description>中国的首都</description>
  </city>
  <city>
    <id>2</id>
    <name>深圳</name>
    <description>经济繁荣</description>
  </city>
  <city>
    <id>3</id>
    <name>广州</name>
    <description>很大的城市</description>
  </city>
  <city>
    <id>4</id>
    <name>香港</name>
    <description>亚洲金融中心</description>
  </city>
  <province>
    <id>1</id>
    <name>广东省</name>
    <city>
      <id>5</id>
      <name>佛山</name>
      <description>功夫之地</description>
    </city>
  <city>
      <id>6</id>
      <name>河源</name>
      <description>天是蓝的</description>
    </city>
  </province>
</China>

2、创建一个对应city.xml的sampldata类

代码如下:

    public class City
    {
        private int id;

        public int Id
        {
            get { return id; }
            set { id = value; }
        }
        private string  name;

        public string  Name
        {
            get { return name; }
            set { name = value; }
        }
        private string  description;

        public string  Description
        {
            get { return description; }
            set { description = value; }
        }       
    }
    public class Province//这个是为了测试
    {
        private int id;

        public int Id
        {
            get { return id; }
            set { id = value; }
        }
        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        private List<City> cities;

        public List<City> Cities
        {
            get { return cities; }
            set { cities = value; }
        }

3、UI布局(在WP8.1上,布局效果可以更好看点)

MainPage.xmal代码如下:

            <StackPanel Orientation="Horizontal">
                <Button Name="getxml" Content="获取数据1" Width="100" Height="40" VerticalAlignment="Top" Click="getxml_Click"/>
                <Button Name="getxml2" Content="获取数据2" Width="100" Height="40" VerticalAlignment="Top" Click="getxml2_Click" Margin="80,0,0,0"/>
            </StackPanel>
            <ListView x:Name="datalist" Margin="0, 50,0,0">
                <ListView.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="{Binding Id}" Style="{ThemeResource TitleTextBlockStyle}"/>
                            <StackPanel Orientation="Vertical">
                                <TextBlock Text="{Binding Name}" Style="{ThemeResource ListViewItemContentTextBlockStyle}"/>
                                <TextBlock Text="{Binding Description}" Style="{ThemeResource BodyTextBlockStyle}"/>
                            </StackPanel>
                        </StackPanel>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>

4、后台具体代码

Note:这里需要 using System.Xml.Linq;

两个Button的点击事件代码如下:

private async void getxml_Click(object sender, RoutedEventArgs e)
        {
            //在windows8.1中还可以获取xml文件,但在WP8.1会出错,我不知道为什么,求解释
            //string path = Path.Combine(Package.Current.InstalledLocation.Path, "DataModel/city.xml");//文件Uri
            //XDocument xmlfile = XDocument.Load(path);

            //在Windows8.1和WP8.1中都可以执行,获取xml文件
            XDocument xmlfile;
            Uri fileUri = new Uri(@"ms-appx:///DataModel/city.xml");//ms-appx:// 为安装目录
            var file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(fileUri);//获取city.xml文件, XDocument.Load()可利用stream,Uri,xmlreader等几种方法获取文件
            using (var stream = await file.OpenStreamForReadAsync())//文件操作都要转换成流
            {
                xmlfile = XDocument.Load(stream);
            };

            var data = from query in xmlfile.Descendants("city")//获取city.xml中所有名为city节点
                       select new City
                       {
                           Id = (int)query.Element("id"),
                           Name = (string)query.Element("name"),
                           Description = (string)query.Element("description")
                       };
            datalist.ItemsSource = data;
        }

        private async void getxml2_Click(object sender, RoutedEventArgs e)
        {
            datalist.ItemsSource = null;
            XDocument xmlfile;
            Uri fileUri = new Uri(@"ms-appx:///DataModel/city.xml");//ms-appx:// 为安装目录
            var file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(fileUri);//获取city.xml文件
            using (var stream = await file.OpenStreamForReadAsync())//文件操作都要转换成流
            {
                xmlfile = XDocument.Load(stream);
            };
            var data = from query in xmlfile.Descendants("city")
                       where (string)query.Parent.Element("name") =="广东省"//linq to xml 选择id<3的city
                       orderby (int)query.Element("id")
                       select new City
                       {
                           Id = (int)query.Element("id"),
                           Name = (string)query.Element("name"),
                           Description = (string)query.Element("description")
                       };
            datalist.ItemsSource = data;                       
        }

上面主要运用了Linq to xml, 需要注意的是Windows8.1和WP8.1在获取xml文件的方法有点差异,或者我哪里弄错了,请大家指出。还有请大家教下我怎样利用LINQ把province节点的数据绑定到Province类上,并给data赋值。

运行效果:

点击获取数据1按钮,效果如图:                  点击获取数据2按钮,效果如图:

                         

-----------------------------------------------------------------------------------------------------------个人总结

写完了这个知识积累了,自学这些编程真的有点学得慢,有个人带就好了啊。又要去复习集成电源和嵌入式了,为了明天下午的考试=.=还有明天上午要去财富世纪广场面试.Net实习生了,不知道凭借自己的现在的知识能不能通过,希望顺顺利利。

原文地址:https://www.cnblogs.com/NEIL-X/p/4221319.html