LCL
LCL

Reputation: 125

Selecting multiple children using where clause in linq for xml

I have this bit of XML

<status complete="false">
  <messages>
    <message>Message 1</message>
    <message>Message 2</message>
    <message>Message 3</message>
  </messages>
</status>

which looks like this when there are no messages

<status complete="false">
  <messages/>
</status>

or could also look like this

<status complete="false">
  <messages>
    <message/>
  </messages>
</status>

I want to be able to parse the messages ("Message 1", "Message 2" and "Message 3") if they are available but I'm having some trouble and I'm only getting the first message. This is the bit of C# that I'm using:

var feeds = from feed in xmlDoc.Descendants("messages")
            where (feed.Element("message") != null)
            select new
            {
                Message = feed.Element("message").Value
            };

foreach (var feed in feeds)
{
    Debug.WriteLine("Found a message");
}

Could any .NET ninja please tell me what kind of noobie mistake I'm making. Any help will be greatly appreciated.

Cheers

Luis

Upvotes: 0

Views: 1089

Answers (2)

Anton Semenov
Anton Semenov

Reputation: 6347

Your query is too complex, try this:

var feeds = from feed in doc.Descendants("message")
select new
{
  Message = feed.Value
};

Upvotes: 1

Rob Windsor
Rob Windsor

Reputation: 6859

I think this will do the trick

var feeds = from feed in xmlDoc.Descendants("message")
            where feed.IsEmpty == false
            select feed;

Upvotes: 1

Related Questions