【问题标题】:Querying XML document using Linq使用 Linq 查询 XML 文档
【发布时间】:2012-10-31 02:44:27
【问题描述】:

我正在尝试 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();
  }
 }

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 如前所述,您应该查看Descendants 而不是Attributes
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多