0

I am using Visual Studio 2013, C#...

I have this XML in variable 'myXml':

<root>
<article><title>A1</title><category><title>Geography</title></category></article>
<article><title>A2</title><category><title>History</title></category></article>
<article><title>A3</title><category><title>Geography</title></category></article>
<article><title>A4</title><category><title>Finance</title></category></article>
</root>

How can I retrieve each which has a category title of "Finance" using LINQ2XML, as either a lambda or plain LINQ query?

I have this LINQ query which does not work:

var doc = XDocument.Parse(myXml);

var l = (from d in doc.Elements("root").Elements("article")
                    where d.Elements("category").Elements("title").Equals("Finance")
                    select d);
Marek Woźniak
  • 1,766
  • 16
  • 34
Matt W
  • 11,753
  • 25
  • 118
  • 215

3 Answers3

1

Simple XPath solution will be

 var l = doc.XPathSelectElements("/root/article[category/title/text() = \"Finance\"]");

Alernatively,

var l = (from d in elem.Element("root")
            .Elements("article")
            .Elements("category")
            .Elements("title")
            .Where(x => x.Value == "Finance")
            select d.Parent.Parent);
vikas
  • 931
  • 6
  • 11
0

I believe this should do it for you

 var l = from att in XDocument.Parse(myXml)
                .Element("root")
                .Elements("article")
                .Elements("category")
                .Where(x => x.Value == "Finance")
                select att;
sjramsay
  • 555
  • 1
  • 5
  • 12
0

it works fine:

        var query = from article in doc.Descendants("article")
                    where ((string)article.Element("category").Element("title").Value == "Finance")
                    select article;

The method Equals is not for comparison with other object by your parameter. Please look here: Distinct not working with LINQ to Objects

Community
  • 1
  • 1
Marek Woźniak
  • 1,766
  • 16
  • 34