Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a XML child element exists with Linq to XML

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

like image 346
Ola Karlsson Avatar asked Jul 28 '09 08:07

Ola Karlsson


3 Answers

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();
like image 86
dahlbyk Avatar answered Nov 13 '22 20:11

dahlbyk


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

like image 20
marc_s Avatar answered Nov 13 '22 19:11

marc_s


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

like image 1
M Worsfold Avatar answered Nov 13 '22 19:11

M Worsfold