Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read attributes values with linq

I have an xml file that looks like the following. What I'm trying to do is to create a query that selects only the items with the attribute "Channel" and the value "Automotive".

<item>
      <title>Industries</title>
      <category type="Channel">Automotive</category>
      <category type="Type">Cars</category>
      <category type="Token">Article</category>
      <category type="SpecialToken">News</category>
      <guid>637f0dd7-57a0-4001-8272-f0fba60feba1</guid>
</item>

Here is my code

 var feeds = (from item in doc.Descendants("item")
    where item.Element("category").Value == "Channel"  
    select new { }).ToList(); 

I tried using the item.attribute method but I can't get to the value within the Item, only the attribute Value of "type"

Could somebody please help me out on this?

Cheers, Chris

like image 606
Chris Avatar asked Aug 08 '26 13:08

Chris


1 Answers

I suspect you want:

var feeds = (from item in doc.Descendants("item")
             from category in item.Elements("category")
             where category.Value=="Automotive" && 
                   category.Attribute("type").Value == "Channel"
             select item).ToList();
like image 98
Jon Skeet Avatar answered Aug 10 '26 19:08

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!