Reputation: 12434
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);
Upvotes: 0
Views: 41
Reputation: 939
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);
Upvotes: 1
Reputation: 1786
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
Upvotes: 0
Reputation: 555
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;
Upvotes: 0