Tanuj Wadhwa
Tanuj Wadhwa

Reputation: 2045

Basic filtering in LINQ to XML Queries

I am new to XDocument and LINQ. Here is what I am trying to do :

XML file :

<?xml version="1.0" encoding="utf-8"?>
<root>
  <chapters total-chapters="3">
    <Chapter chapter-no="1">
      <chapter-summary>this is chapter 1</chapter-summary>
    </Chapter>
    <Chapter chapter-no="2">
      <chapter-summary>this is chapter 2</chapter-summary>
    </Chapter>
    <Chapter chapter-no="3">
      <chapter-summary>this is chapter 3</chapter-summary>
    </Chapter>
    <Chapter chapter-no="4">
      <chapter-summary>this is chapter 4</chapter-summary>
    </Chapter>
</chapters>
</root>

Now I need to read all the records with a specific chapter-no. I am writing my LINQ query as :

IEnumerable<XElement> elem_list = 
    from e in xdoc.Elements("Chapter") 
    where (string) e.Attribute("chapter-no") == "1" 
    select e;

foreach (XElement e in elem_list)
{
    Console.WriteLine(e);
}

but elem_list is not getting populated and nothing is displayed.

Upvotes: 0

Views: 1215

Answers (2)

Garett
Garett

Reputation: 16828

You can do something like the following:

IEnumerable<XElement> elem_list = 
   xdoc.Descendants("Chapter")
   .Where (c => c.Attribute("chapter-no").Value.Equals("1"));

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

.Elements("Chapter") search only within direct children of current element (root for xdoc).

You can use .Descendants("Chapter"):

IEnumerable<XElement> elem_list = from e in xdoc.Descendants("Chapter")
                                  where (string) e.Attribute("chapter-no") == "1"
                                  select e;

Or specify full item path:

IEnumerable<XElement> elem_list = from e in xdoc.Root.Element("chapters").Elements("Chapter")
                                  where (string) e.Attribute("chapter-no") == "1"
                                  select e;

Another approach - with XPath selector:

xdoc.XPathSelectElements("root/chapters/Chapter[@chapter-no=1]");

using System.Xml.XPath; is necessary to make the last sample work.

Upvotes: 2

Related Questions