乱舞WindowsPhone——xml文件读取
Windows Phone中的xml文件不能像传统.net中通过XmlDocument进行操作,以下介绍几种常用的xml操作方式:
1:通过Linq to Xml读取xml (Resource)
首先创建用于测试的xml文件,并将该文件的生成操作设置为Resource,创建对应的实体类;
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?xml version="1.0"?> <Root> <LoginRequest> <Uid>yonghu1</Uid> <Password>123456</Password> </LoginRequest> <LoginRequest> <Uid>yonghu2</Uid> <Password>123456</Password> </LoginRequest> <LoginRequest> <Uid>yonghu3</Uid> <Password>123456</Password> </LoginRequest> </Root>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class LoginRequest { public String Uid { get; set; } public String Password { get; set; } }
其次引用System.Xml.Linq;
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 var stream = Application.GetResourceStream(new Uri("/BlogTest;component/xml/Login.xml", UriKind.Relative)); 2 XElement element = XElement.Load(stream.Stream); 3 var loginList = (from el in element.Descendants("LoginRequest") 4 select new LoginRequest 5 { 6 Uid = el.Element("Uid").Value, 7 Password = el.Element("Password").Value 8 }).ToArray();
2:通过XmlReader方式读取xml
这种方法通过比对节点Name以及节点NodeType来寻找自己需要解析的内容
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
var reader = XmlReader.Create(stream.Stream); var loginList = new List<LoginRequest>(); while (reader.Read()) { if(reader.NodeType==XmlNodeType.Element) { if(reader.Name=="LoginRequest") { var loginRequest = new LoginRequest(); while (reader.Read() && reader.NodeType!=XmlNodeType.EndElement) { if(reader.Name=="Uid") { if(reader.Read()) { loginRequest.Uid = reader.Value; } } } while (reader.Read() && reader.NodeType != XmlNodeType.EndElement) { if (reader.Name == "Password") { if (reader.Read()) { loginRequest.Password = reader.Value; } } } loginList.Add(loginRequest); } } }
3:反序列化方式获取xml
这种方式常用于读取保存后的序列化xml文件,见以下链接:
http://www.cnblogs.com/zdave/archive/2011/06/01/2067282.html