LINQ To XML定位方法

开发 后端
这里介绍LINQ To XML——定位方法,包括Ancestors:返回指定节点的所有上级元素、Descendants:返回所有指定元素名称的后续所有相同元素集合等方面。

LINQ有很多值得学习的地方,这里我们主要介绍LINQ To XML,包括介绍LINQ To XML——定位方法等方面。

LINQ To XML定位方法

1.LINQ To XML定位方法——Ancestors:返回指定节点的所有上级元素。(AncestorsAndSelf:返回包括自己的所有上级元素)

  1. XElement Students = new XElement("Students",  
  2. new XElement("Student"  
  3. new XElement("Name", "张三"),  
  4. new XElement("Sex", "男"),  
  5. new XElement("Age",new XAttribute ("Year","1989/8/22"), 20))  
  6. );  
  7. foreach (var el in Students.Element ("Student").Element("Sex").Ancestors ())  
  8. {  
  9. Console.WriteLine(el);  

2.LINQ To XML定位方法——Descendants:返回所有指定元素名称的后续所有相同元素集合。

  1. XElement Students = new XElement("Students",  
  2. new XElement("Student",  
  3. new XElement("Name", "张三"),  
  4. new XElement("Sex", "男"),  
  5. new XElement("Age", new XAttribute("Year", "1989/8/22"), 20)),  
  6. new XElement("Student",  
  7. new XElement("Name", "李四"),  
  8. new XElement("Sex", "女"),  
  9. new XElement("Age", new XAttribute("Year", "1990/8/22"), 20))  
  10. );  
  11. foreach (var v in Students.Descendants())  
  12. {  
  13. Console.WriteLine(v);  
  14. Console.WriteLine("-----------------------");  

3.LINQ To XML定位方法——ElementsAfterSelf:返回当前节点后的所有节点。(ElementsBeforeSelft:返回当前节点前的所有节点)

  1. XElement Students = new XElement("Students",  
  2. new XElement("Student",  
  3. new XElement("Name", "张三"),  
  4. new XElement("Sex", "男"),  
  5. new XElement("Age", new XAttribute("Year", "1989/8/22"), 20)),  
  6. new XElement("Student",  
  7. new XElement("Name", "李四"),  
  8. new XElement("Sex", "女"),  
  9. new XElement("Age", new XAttribute("Year", "1990/8/22"), 20))  
  10. );  
  11. foreach (var v in Students.Element ("Student").ElementsAfterSelf ())  
  12. {  
  13. Console.WriteLine(v);  
  14. Console.WriteLine("-----------------------");  
  15. }

【编辑推荐】

  1. LINQ查询操作剖析
  2. LINQ生成字符串概述
  3. LINQ查询语法简单描述
  4. LINQ解决方案简单概述
  5. LINQ查询结果分析
责任编辑:佚名 来源: CSDN
相关推荐

2011-07-22 08:43:08

XML

2009-09-17 13:54:26

LINQ to XML

2009-09-17 13:30:32

LINQ to XML

2009-01-04 16:58:48

LINQ to XMLLINQXML

2009-09-16 16:59:05

LINQ to XML

2009-09-14 16:46:15

LINQ to XML

2009-09-16 16:52:50

LINQ to XML

2009-09-16 15:33:22

LINQ to XML

2011-07-26 13:58:17

LINQ

2009-09-14 15:12:40

LINQ to XML

2009-09-14 16:33:55

LINQ To XML

2009-09-08 16:55:01

Linq实现XML转换

2009-09-16 16:55:07

LINQ to XML

2009-09-16 15:41:45

LINQ查询XML文档

2009-09-14 16:51:33

LINQ XML树加载

2009-09-16 15:53:49

Linq创建xml文档

2009-09-16 15:48:05

Linq修改XML文档

2009-09-14 14:58:52

LINQ to XML

2009-09-17 13:38:42

LINQ to XML

2009-09-14 16:17:03

什么是LINQ To
点赞
收藏

51CTO技术栈公众号