1

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.

1
  • Is it XmlElement or XElement? Commented Mar 13, 2017 at 23:22

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

2 Comments

But this gives me GreenWhite. Just as before.
@user1017102: Fixed - need to select category.Value and not item.Value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.