Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if XElement.Elements() contains a node with a specific name?

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.

like image 227
Malik Daud Ahmad Khokhar Avatar asked Oct 27 '08 13:10

Malik Daud Ahmad Khokhar


People also ask

How to get XElement attribute value in c#?

If you are getting the value and the attribute might not exist, it is more convenient to use the explicit conversion operators, and assign the attribute to a nullable type such as string or Nullable<T> of Int32 . If the attribute does not exist, then the nullable type is set to null.

How to find XML element in c#?

The simplest way to search XML is to use the Linq-to-XML API in . NET (in System. Xml.


2 Answers

Just use the other overload for Elements.

bool hasCity = OrderXml.Elements("City").Any(); 
like image 70
Amy B Avatar answered Sep 21 '22 09:09

Amy B


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 

;

like image 36
James Curran Avatar answered Sep 18 '22 09:09

James Curran