PHP DomElement:查看element是否是另一个元素的直接或间接子元素


PHP DomElement: See if element is a direct or indirect child of another element

假设我有以下XML:

<family>
    <father>
        <date_of_birth>1971-01-25</date_of_birth>
        <first_name>Bob</first_name>
        <last_name>Johnson</last_name>
    </father>
    <mother>
        <date_of_birth>1977-09-12</date_of_birth>
        <first_name>Mary</first_name>
        <last_name>Johnson</last_name>
    </mother>
    <child>
        <date_of_birth>2006-04-21</date_of_birth>
        <first_name>Pete</first_name>
        <last_name>Johnson</last_name>
    </child>
</family>

我决定只使用<date_of_birth>值。我做了以下操作:

$DOBs = $dom->getElementsByTagName("date_of_birth");

现在,我的问题是,当我循环遍历值时:

foreach ($DOBs as $date)
{
    echo $date->nodeValue . "<br>";
}

我怎么知道这些值是来自母亲、父亲还是孩子?是否有办法检查DomElement $日期是否是母亲或父亲的孩子或孙子?基本上,我需要知道这些是否在标签内(无论有多深)。

编辑

例如(请注意is_child_of方法是虚构的):

foreach ($DOBs as $date)
{
    if($date->is_child_of('father'))
    {
        //This is the father's date of birth.
    }
}

我正在寻找的东西,告诉我这个<date_of_birth>是在另一个元素。所以如果我输入:

if($date->is_child_of('family'))
{
}

if($date->is_child_of('father'))
{
}

这两个都为真(假设我们处理的是父亲的date_of_birth),并且if语句中的代码将触发。

如果您只寻找直接父级,请使用DOMNode实例的parentNodenodeName属性。

对于间接父节点,除了使用XPath之外,我只知道这个函数:

function isChildOf(DOMNode $childNode, $parentNodeName)
{
    while ($childNode->parentNode)
    {
        if ($childNode->parentNode->nodeName == $parentNodeName) {
            return true;
        }
        else {
            $childNode = $childNode->parentNode;
        }
    }
    return false;
}

未经测试,使用风险自负