Checking if a XML child element exists with Linq to XML

15,814

Solution 1

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

Solution 2

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

Solution 3

in Linq to xml you can do this quick check before getting a value:

if (!xe.Root.Element("Date").IsEmpty)
{
    pd.datefield = System.Convert.ToString(xe.Root.Element("Date").Value);
}

doesn't work with NULL data in the database as it doesn't create the tags with empty data

for that you would have to loop through the child elements

Share:
15,814
Dave Clark
Author by

Dave Clark

Teacher, developer, speaker, trainer, UX enthusiast and ocean lover.

Updated on June 16, 2022

Comments

  • Dave Clark
    Dave Clark almost 2 years

    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