当前位置: 移动技术网 > IT编程>移动开发>WP > Windows Phone 实用开发技巧(25):Windows Phone读取本地数据

Windows Phone 实用开发技巧(25):Windows Phone读取本地数据

2018年10月09日  | 移动技术网IT编程  | 我要评论

人心果,麻辣除灵师,yzwb

windows phone read local data

during windows phone development, sometimes we might be want to read some initial data from local resources. data can be stored in xml, json, txt or other formats. unlike data files stored in isolatedstorage, we cannot make changes to them or delete them (since they are built in content or resource). which format is better ? well, it depends. so let me make a simple demo to show you how we read initial data in windows phone.

read xml files

assuming that we have following xml file
 
<?xml version="1.0" encoding="utf-8" ?>
<students>
  <student>
    <name>alexis</name>
    <age>12</age>
    <no>007</no>
  </student>
  <student>
    <name>tomcat</name>
    <age>20</age>
    <no>62</no>
  </student>
  <student>
    <name>jacky</name>
    <age>32</age>
    <no>001</no>
  </student>
  <student>
    <name>selina</name>
    <age>24</age>
    <no>033</no>
  </student>
</students>
the root element is students which has four child element student. how can we load them in windows phone .we can do that in many ways. before we do that we create student class first.
public class student
{
    public string name { get; set; }
 
    public int age { get; set; }
 
    public string no { get; set; }
}


 

way 1.  add system.xml.linq reference

then we can use following code to load students in one collection


xelement root = xelement.load("students.xml");
if (root != null)
{
     var items = from student in root.descendants("student")
                 select new student
                 {
                    age = convert.toint32(student.element("age").value),
                    name = student.element("name").value,
                    no = student.element("no").value,
                  };
     listbox1.itemssource = items;
}
remeber to set students.xml build action to content.
way 2. use application.getresourcestream
var streaminfo = application.getresourcestream(new uri("students.xml", urikind.relative));
using (var stream=streaminfo.stream)
{
    xelement root = xelement.load(stream);
    if (root != null)
    {
       var items = from student in root.descendants("student")
                   select new student
                   {
                      age = convert.toint32(student.element("age").value),
                      name = student.element("name").value,
                      no = student.element("no").value,
                    };
        listbox1.itemssource = items;
     }
}




note: that application.getresourcestream is suitable for all file format.

we can use application.getresourcestream to load txt files, json files , dat files and whatever format. what you need to do is prepare data and read the file stream, convert to what you want.

you can find source 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网