Search code examples
c#xmllinqxelement

Check if XElement with particular value exist


For example for the following XML

 <Tree>   

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

   <Order>
    <Phone>765</Phone>
    <City>City2</City>
    <State>State3</State>
   </Order>   

  </Tree>

I might want to find out whether the XElement "Tree" contains "Order" Node with the value "City2" in its "City" child-node.

The following code returns whether the XElement City is exist, but does not check its value, How can I update it so that it meets my request?

bool exists = Tree.Elements("Order").Elements("City").Any();

Solution

  • There's an Any overload which accepts a predicate, so you just need to use that:

    bool exists = Tree.Elements("Order")
                      .Elements("City")
                      .Any(x => x.Value == "City2");
    

    Alternatively, use Where before Any:

    bool exists = Tree.Elements("Order")
                      .Elements("City")
                      .Where(x => x.Value == "City2")
                      .Any();
    

    Basically, just remember that you've got the whole of LINQ to Objects available to you.