Ramesh Sivaraman
Ramesh Sivaraman

Reputation: 1305

Querying XML document using Linq

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.

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

Upvotes: 2

Views: 26675

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81253

Replace your LINQ where query with this one -

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

Upvotes: 4

Related Questions