LINQ有很多值得学习的地方,这里我们主要介绍LINQ To XML,包括介绍LINQ To XML——定位方法等方面。
LINQ To XML定位方法
1.LINQ To XML定位方法——Ancestors:返回指定节点的所有上级元素。(AncestorsAndSelf:返回包括自己的所有上级元素)
- XElement Students = new XElement("Students",
- new XElement("Student"
- new XElement("Name", "张三"),
- new XElement("Sex", "男"),
- new XElement("Age",new XAttribute ("Year","1989/8/22"), 20))
- );
- foreach (var el in Students.Element ("Student").Element("Sex").Ancestors ())
- {
- Console.WriteLine(el);
- }
2.LINQ To XML定位方法——Descendants:返回所有指定元素名称的后续所有相同元素集合。
- XElement Students = new XElement("Students",
- new XElement("Student",
- new XElement("Name", "张三"),
- new XElement("Sex", "男"),
- new XElement("Age", new XAttribute("Year", "1989/8/22"), 20)),
- new XElement("Student",
- new XElement("Name", "李四"),
- new XElement("Sex", "女"),
- new XElement("Age", new XAttribute("Year", "1990/8/22"), 20))
- );
- foreach (var v in Students.Descendants())
- {
- Console.WriteLine(v);
- Console.WriteLine("-----------------------");
- }
3.LINQ To XML定位方法——ElementsAfterSelf:返回当前节点后的所有节点。(ElementsBeforeSelft:返回当前节点前的所有节点)
- XElement Students = new XElement("Students",
- new XElement("Student",
- new XElement("Name", "张三"),
- new XElement("Sex", "男"),
- new XElement("Age", new XAttribute("Year", "1989/8/22"), 20)),
- new XElement("Student",
- new XElement("Name", "李四"),
- new XElement("Sex", "女"),
- new XElement("Age", new XAttribute("Year", "1990/8/22"), 20))
- );
- foreach (var v in Students.Element ("Student").ElementsAfterSelf ())
- {
- Console.WriteLine(v);
- Console.WriteLine("-----------------------");
- }
【编辑推荐】