Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用Linq查询XML文档_C#_Xml_Linq_Xml Parsing_Linq To Xml - Fatal编程技术网

C# 使用Linq查询XML文档

C# 使用Linq查询XML文档,c#,xml,linq,xml-parsing,linq-to-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>

我正在尝试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"));
将LINQ where查询替换为此查询-

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

如前所述,您应该查看子体而不是属性。如前所述,您应该查看子体而不是属性。