Windows Phone 实用开发技巧(25):Windows Phone读取本地数据
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
推荐阅读
-
Windows Phone实用开发技巧(31):密码加密
-
Windows Phone 实用开发技巧(29):动态绑定Pivot
-
Windows Phone实用开发技巧(32):照片角度处理
-
Windows Phone实用开发技巧(33):不重启程序切换当前语言
-
Windows Phone 实用开发技巧(2):使用TombstoneHelper简化墓碑操作
-
Windows Phone实用开发技巧(1):保存图片及加载图片
-
Windows Phone 实用开发技巧(17):自定义应用程序的Tile
-
Windows Phone 实用开发技巧(3):输入框自动聚焦并打开SIP
-
Windows Phone 实用开发技巧(25):Windows Phone读取本地数据
-
Windows Phone 实用开发技巧(18):使用SystemTray显示全局消息提醒