简体   繁体   中英

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

I think this will do the trick

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

Your query is too complex, try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM