c# - 使用 Linq 查询 XML 文档

标签 c# xml linq xml-parsing linq-to-xml

我正在尝试 Linq 一个 xml 文档,我无法查询内部元素,您可以从下面的代码中看到我正在尝试执行的操作。我想获取具有特定名称的所有记录...请帮忙。

<?xml version="1.0" encoding="utf-8" ?>
<Student>

 <Person name="John" city="Auckland" country="NZ" />

 <Person>
    <Course>GDICT-CN</Course>
    <Level>7</Level>
    <Credit>120</Credit>
    <Date>129971035565221298</Date>
 </Person>
 <Person>
    <Course>GDICT-CN</Course>
    <Level>7</Level>
    <Credit>120</Credit>
    <Date>129971036040828501</Date>
 </Person>
</Student>

现在是来源

class Program
{
  static void Main(string[] args)
  {
     string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
     XDocument xDoc = XDocument.Load(path + "\\Student Data\\data.xml");

     IEnumerable<XElement> rows = 
        from row in xDoc.Descendants("Person")
             where (string)row.Attribute("Course") == "GDICT-CN"
             select row;

     foreach(XElement xEle in rows)
     {
        IEnumerable<XAttribute>attlist = 
          from att in xEle.DescendantsAndSelf().Attributes() 
               select att;

        foreach(XAttribute xatt in attlist)
        {
            Console.WriteLine(xatt);
        }
        foreach (XElement elemnt in xEle.Descendants())
        {
             Console.WriteLine(elemnt.Value);
        }
        Console.WriteLine("-------------------------------------------");
      }
   Console.ReadLine();
  }
 }

最佳答案

将您的 LINQ where 查询替换为此查询 -

IEnumerable<XElement> rows = xDoc.Descendants().Where(d => d.Name == "Person"
                               && d.Descendants().Any(e => e.Name == "Course"
                                 && e.Value == "GDICT-CN"));

关于c# - 使用 Linq 查询 XML 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13330796/

相关文章:

c# - 如何在不锁定数据库的情况下使用数据读取器执行 SQLite 查询?

xml - ScrollView 包装的 Nativescript GridLayout

mysql - 如何使用 XSL 模板清理 Mysql 查询?

xml - 使用 Scala 提取具有特定子元素内容的 XML 元素

c# - 从文件中读取字节

c# - 解析 csv 以基于一个字段创建没有重复条目的查询

c# - 如何将 C# GUI 添加到 C++ 代码?

c# - 将 IOrderedEnumerable 排序为任意顺序

c# - 使用 LINQ,获取满足分组条件的项目数

c# - 匿名方法 vs 扩展方法 vs Lambda 表达式 vs Linq