C# LINQ 基础 互动版

在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器

查询XML结点

  Linq是从集合中查询对象,在linq to xml中的集合是通过XElement类的Elements(),Elements(string name),以及Descendants、DescendantsAndSelf、Ancestors、AncestorsAndSelf的几个重载方法中获得。获得XElement集合之后,可以通过XElementAttribute(string name)方法获得元素的属性值,可以通过XElementValue属性获得节点的文本值;

 static void Main(string[] args)
 {
    string xmlString = @"<persons>
                             <person>
                                 <name>John</name>
                                 <age>28</age>
                             </person>
                         </persons>";
    XElement xe = XElement.Parse(xmlString,LoadOptions.SetLineInfo);
    //读取元素  读取Name的后面的第一个兄弟元素
    XElement xe1 = xe.Element("person").Element("name").ElementsAfterSelf().First();
    Console.WriteLine(xe1.Value);   //输出 28
    //读取父节点
    XElement xe2 = xe1.Parent;
    Console.WriteLine(xe2.Name);
}