30

For example for the following XML

 <Order>
  <Phone>1254</Phone>
  <City>City1</City>
  <State>State</State>
 </Order>

I might want to find out whether the XElement contains "City" Node or not.

Malik Daud Ahmad Khokhar
  • 13,470
  • 24
  • 79
  • 81

3 Answers3

61

Just use the other overload for Elements.

bool hasCity = OrderXml.Elements("City").Any();
Amy B
  • 108,202
  • 21
  • 135
  • 185
  • 3
    Or use Descendants("MyNode").Any() if you don't care about where it is in the tree. – jcollum Dec 31 '09 at 21:47
  • 1
    CS1061: 'System.Collections.Generic.IEnumerable' does not contain a definition for 'Any' – Alan Baljeu May 06 '16 at 20:10
  • 1
    @AlanBaljeu add "using System.Linq" at the top of the file. This allows the extension method System.Linq.Enumerable.Any to be used. – Amy B May 06 '16 at 23:35
4

It's been a while since I did XLinq, but here goes my WAG:

from x in XDocument
where x.Elements("City").Count > 0
select x

;

James Curran
  • 101,701
  • 37
  • 181
  • 258
1

David's is the best but if you want you can write your own predicate if you need some custom logic OrderXML.Elements("City").Exists(x=>x.Name =="City")

Mark
  • 19
  • 2