简体   繁体   English

使用linq中的where子句为xml选择多个子节点

[英]Selecting multiple children using where clause in linq for xml

I have this bit of XML 我有这个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. 我希望能够解析消息(“消息1”,“消息2”和“消息3”),如果它们可用但我遇到了一些麻烦,我只收到第一条消息。 This is the bit of C# that I'm using: 这是我正在使用的C#:

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. 任何.NET忍者都可以告诉我,我正在犯的是什么样的noobie错误。 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
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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