欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2022-08-21 14:15:10
windows phone read local data during windows phone development, sometimes we might be want to read...

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 here