Checking if a XML child element exists with Linq to XML

linq, linq-to-xml, xml

Solution

Here's a query approach:

XElement yourDoc = XElement.Load("your file name.xml");

bool hasPhone = (
    from user in yourDoc.Descendants("user")
    where (int)user.Attribute("id") == 2
    select user.Descendants("phone").Any()
    ).Single();

Problem

I'm trying to get my head around a problem I'm having in Linq to XML, seems like it should be pretty simple but even after browsing the Linq to XML questions here, I can't quite get it. Take something along the lines of the following XML: ``` <users> <user id="1"> <contactDetails> <phone number="555 555 555" /> </contactDetails> </user> <user id="2"> <contactDetails /> </user> </users> ``` I now want to check if user with id 2 has a phone number. Could someone suggest a solution, as I said seems, like it should be simple... Cheers, Ola

Original source