user1017102
user1017102

Reputation: 807

Reading an XML Element using LINQ

I am trying to read a value from an XML file using LINQ. This is really the first time that I am trying to use LINQ vs. the ordinary C#/.Net approach.

My XML looks like this:

<Description>
<Account Green="A" White="D">House</Account>
<Account Green="B" White="D">Car</Account>
</Description>

This is the LINQexpression I am using. I'd like to read the value House, in other words, the element with the attribute A and D.

var feeds = (from item in doc.Descendants("Description")
 from category in item.Elements("Account")                    
 let attribute = category.Attribute("Green")                    
 let xAttribute = category.Attribute("White")                    
 where attribute != null && (xAttribute != null && (xAttribute.Value == "A" 
 && attribute.Value == "D")) select item.Value).ToString();   

I can't figure out what I am doing wrong. Any help is appreciated.

Upvotes: 1

Views: 4038

Answers (1)

BrokenGlass
BrokenGlass

Reputation: 161012

You have an IEnumerable<string> here - you apparently just want a single string here so add a First() to get the value of the first item in your enumeration:

var feeds = (from item in doc.Descendants("Description")
 from category in item.Elements("Account")                    
 let attribute = category.Attribute("Green")                    
 let xAttribute = category.Attribute("White")                    
 where attribute != null && (xAttribute != null && (xAttribute.Value == "A" 
 && attribute.Value == "D")) select category.Value).First(); 

An easier way to achieve the same might be:

string result = doc.Descendants("Account")
                   .Where(x => x.Attribute("Green") != null && x.Attribute("Green").Value == "A"
                            && x.Attribute("White") != null && x.Attribute("White").Value == "D")
                   .Select(x => x.Value)
                   .First();

Upvotes: 1

Related Questions