Linq操作XML,查找节点数据

来源:互联网 发布:氰化钾淘宝叫什么 编辑:程序博客网 时间:2024/05/16 05:45
[csharp] view plain copy
 print?
  1. /*查找XML*/  
  2. var filePath = Server.MapPath("~/xml/sample.xml");  
  3. XDocument doc = XDocument.Load(filePath);  
  4. var text1 = doc.Descendants("用户")  //定位到节点   
  5.                 .Where(p => p.Element("性别").Value.Contains('男')) //若要筛选就用上这个语句   
  6.                 .Select(p => new { name = p.Element("姓名").Value });  
  7. foreach (var a in text1)  
  8. {  
  9.     str += a.name + "<br/>";  
  10. }  
  11.   
  12. /*结果*/  
  13. 张三  
  14. 李四  
[html] view plain copy
 print?
  1. <?xml version="1.0" encoding="gb2312" standalone="yes"?>  
  2. <班级信息>  
  3.   <用户>  
  4.     <姓名>张三</姓名>  
  5.     <性别></性别>  
  6.   </用户>  
  7.   <用户>  
  8.     <姓名>李四</姓名>  
  9.     <性别></性别>  
  10.   </用户>  
  11.   <用户>  
  12.     <姓名>王琳</姓名>  
  13.     <性别></性别>  
  14.   </用户>  
  15. </班级信息>  
原创粉丝点击