C# 使用 Linq 查询 XML 文档

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13330796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:13:07  来源:igfitidea点击:

Querying XML document using Linq

c#xmllinqxml-parsinglinq-to-xml

提问by Ramesh Sivaraman

I am trying to Linq an xml document, I am unable to query the inner elements as you can see from below code what I am trying to do. I want to get all records which has a certain name... Please help.

我正在尝试 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>

And now the source

现在来源

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();
  }
 }

采纳答案by Rohit Vats

Replace your LINQ wherequery with this one -

LINQ where用这个替换您的查询 -

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