【问题标题】:How to find out, whether a DOMElement/DOMNode is a subnode of a DOMDocument in PHP?如何找出 DOMElement/DOMNode 是否是 PHP 中 DOMDocument 的子节点?
【发布时间】:2013-07-29 01:17:46
【问题描述】:

我有一个DOMElement。我怎样才能知道它是否是 DOMDocument 的子节点?

问题背景:

[A DOMElement 对象] 是只读的。它可以附加到文档中, 但其他节点可能不会附加到该节点,直到该节点 与文档相关联。 (看 here)。


编辑:

DOMNode#getNodePath() 获取节点的 XPath 位置路径。根节点的路径为/。因此一个节点是一个子元素,如果它的位置不等于/

但这仅适用于子节点。如果它是“独立”节点对象,则会引发警告:

$test = new \DOMNode();
echo $test->getNodePath();

警告:DOMNode::getNodePath(): 无法在第 16 行的 /path/too/foo.php 中获取 DOMNode

【问题讨论】:

    标签: php dom domdocument appendchild


    【解决方案1】:

    您应该检查ownerDocument 属性:

    if ($node->ownerDocument === $document) {
        // $node is part of $document
    } else {
        $importedNode = $document->importNode($node, true);
        // now you can append the node wherever you choose in the document
    }
    

    【讨论】:

      【解决方案2】:

      检查类的类型:

      if($dom instanceof \DOMDocument) { ... }
      

      【讨论】:

        猜你喜欢
        • 2011-09-08
        • 2013-11-09
        • 1970-01-01
        • 2014-08-29
        • 2011-01-15
        • 1970-01-01
        • 1970-01-01
        • 2011-01-15
        相关资源
        最近更新 更多