SimpleXmlElement计数

I'm trying to count the amount of children in a SimpleXmlElement. I've searched on StackOverflow but I can't seem to find anything;

$xml = simplexml_load_string($xml);

foreach($xml as $key => $field) {
    if (count($field) == 0){
        $field[0][0] = 'test';
    }
}

Some of my XmlElement are empty. Yet count gives 0 on all the elements. The only way I've found to do what I want is this:

if ($field[0][0] == '')

I've tried using $field->count() as specified on http://php.net/manual/en/simplexmlelement.count.php, but no matter what is in $field, it always returns 0.

Isn't there a better way to do this?

Here is the format of the xml through print_r:

SimpleXMLElement Object
(
    [firstName] => Test
    [lastName] => Test2
    [middleName] => SimpleXMLElement Object
        (
        )
)

You can use the count() function like this:

$elem = new SimpleXMLElement($xml);
$elem->count();

http://php.net/manual/en/simplexmlelement.count.php for reference.