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

43,206

Solution 1

Just use the other overload for Elements.

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

Solution 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

;

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

Share:
43,206
Malik Daud Ahmad Khokhar
Author by

Malik Daud Ahmad Khokhar

Interested in React, Node.js, Hyperledger Fabric/Composer, docker.

Updated on August 18, 2020

Comments

  • Malik Daud Ahmad Khokhar
    Malik Daud Ahmad Khokhar over 3 years

    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.