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 every ways. Before we do that we create student class first.
Public classStudent{Public StringName {Get;Set;}Public intAge {Get;Set;}Public StringNo {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. UseApplication. 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