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; }
}出处:http://www.cnblogs.com/alexis/
本文介绍两种在Windows Phone应用中从XML文件加载学生信息的方法。一种是使用System.Xml.Linq命名空间,另一种则是通过Application.GetResourceStream方法。两种方式均实现了将XML文件中的学生数据解析并展示。

75

被折叠的 条评论
为什么被折叠?



