Sunday, February 13, 2011

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.

  • Just use the other overload for Elements.

    bool hasCity = OrderXml.Elements("City").Any();
    
    Daud : Thnx. This is the one I wanted.
    jcollum : Or use Descendants("MyNode").Any() if you don't care about where it is in the tree.
    From David 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
    

    ;

0 comments:

Post a Comment