views:

1775

answers:

2

Hi people,

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

+1  A: 

There's probably a better and slicker way to do this (I'm not yet awfully familiar with Linq-to-XML), but this code snippet should work:

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

foreach (XElement user in yourDoc.Descendants("user"))
{
    foreach(XElement contact in user.Descendants("contactDetails"))
    {
       var phone = contact.Descendants("phone");

       bool hasPhone = (phone.Count() > 0);
    }
}

It basically enumerates over all "user" nodes in your XML, and then all "contactDetails" nodes inside the user node, and then check to see if there's any "phone" subnodes under that.

The .Descendants() call will return back a list of XElement nodes, and if there are none of the type you inquired about, the .Count() on that list (an IEnumerable<T>) will return 0 - that's what my code is checking for.

Marc

marc_s
+4  A: 

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();
dahlbyk