How to determine if XElement.Elements() contains a

2020-08-09 05:35发布

问题:

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.

回答1:

Just use the other overload for Elements.

bool hasCity = OrderXml.Elements("City").Any();


回答2:

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

;



回答3:

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")