
XML
使用C#的Linq to XML可以方便地对XML文件进行查询和操作。在实际开发中,有时候需要根据某个特定条件获取XML节点的父节点,即获取满足条件的孩子节点的父节点。本文将介绍如何使用Linq to XML来实现这一功能,并通过一个案例代码来加深理解。
案例代码:csharpusing System;using System.Linq;using System.XML.Linq;public class Program{ public static void MAIn() { // 创建一个XML文档 XElement XML = new XElement("Family", new XElement("Parent", new XAttribute("id", 1), new XElement("Name", "John"), new XElement("Child", new XAttribute("id", 1), new XElement("Name", "Alice"), new XElement("Age", 10) ), new XElement("Child", new XAttribute("id", 2), new XElement("Name", "Bob"), new XElement("Age", 12) ) ), new XElement("Parent", new XAttribute("id", 2), new XElement("Name", "Mary"), new XElement("Child", new XAttribute("id", 3), new XElement("Name", "Charlie"), new XElement("Age", 8) ), new XElement("Child", new XAttribute("id", 4), new XElement("Name", "David"), new XElement("Age", 15) ) ) ); // 查询满足条件的孩子节点的父节点 var parents = XML.Descendants("Child") .Where(child => (int)child.Element("Age") > 10) .Select(child => child.Parent) .Distinct(); // 输出结果 foreach (var parent in parents) { Console.WriteLine("父母信息:"); Console.WriteLine("父母姓名:" + parent.Element("Name").Value); Console.WriteLine("父母ID:" + parent.Attribute("id").Value); Console.WriteLine(); } }}在上述案例代码中,我们创建了一个XML文档表示一个家庭的信息,包括父母和孩子的姓名和年龄。我们的目标是根据孩子的年龄大于10岁来获取父母的信息。使用Linq to XML获取父母信息首先,我们使用Descendants方法获取所有的孩子节点,然后使用Where方法筛选出年龄大于10岁的孩子节点。接下来,我们使用Select方法选择孩子节点的父节点。由于可能存在多个孩子满足条件,我们使用Distinct方法去除重复的父节点。输出结果通过遍历获取到的父节点,我们可以输出他们的信息,包括姓名和ID。使用C#的Linq to XML,我们可以轻松地根据孩子节点的条件获取其父节点的信息。这个功能在实际开发中非常实用,可以帮助我们快速定位到需要的数据,并进行相应的操作。通过本文的案例代码,相信读者已经对如何使用Linq to XML获取父节点有了更深入的理解。Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号