【问题标题】:PHP5: Find Root Node in DOMDocumentPHP5:在 DOMDocument 中查找根节点
【发布时间】:2009-07-30 10:31:42
【问题描述】:

我有一个 PHP5 DOMDocument,我试图找到根节点(不是根元素)。

例子:

<test>
    <element>
        <bla1>x</bla1>
        <bla2>x</bla2>
    </element>
    <element>
        <bla1>y</bla1>
        <bla2>y</bla2>
    </element>
    <element>
        <bla1>z</bla1>
        <bla2>z</bla2>
    </element>
</test>

我想获取“test”的 DOMNode,以便我可以调用 - 例如 - hasChildNodes。我可以得到“documentElement”,但那是一个 DOMElement。也许我可以从那里去?

$d = DOMDocument::loadXML($xml);
// [... do some stuff here to find document's root node ...]
if ($rootnode->hasChildNodes()) echo 'yayy!'

谁能填补这个空白?我好像是个盲人。

(显然,我想调用的不仅仅是 hasChildNodes - 所以不,寻找另一种方法来确定文档是否包含内容并没有帮助。这只是我的简单示例。我最后需要一个 DOMNode。 )

【问题讨论】:

  • 好的,问题似乎是 PHP5 和 PHP4 之间的“DOMDocument”和“DomDocument”之间的完全混淆以及它的怪异文档。我想我现在已经修好了。谢谢大家。

标签: php xml dom root-node


【解决方案1】:

DOMElement 扩展了 DOMNode

您通过 $d->documentElement 获得 Root DOMElement

【讨论】:

  • 这实际上应该是勾选的答案!
  • 这里是该属性的文档php.net/manual/en/…
  • 我会为某人节省一次点击。上面的文档说:This is a convenience attribute that allows direct access to the child node that is the document element of the document.
【解决方案2】:

DOM 模型- W3C 已将 DOM 分解为不同类型节点的树形结构。 Node 接口是所有元素的基本接口。所有实现此接口的对象都公开了处理子对象的方法。

$dom=new DomDocument;
$dom->Load("file.xml");
$root=$dom->documentElement; // Root node

【讨论】:

    【解决方案3】:

    根据 PHP 文档DOMElement is a subclass of DOMNode,所以它应该继承hasChildNodes()-方法。

    【讨论】:

    • 嗯,好吧,这实际上是真的......如果我不将我的 ->documentElement 发送到函数,一切似乎都正常......函数调用会丢失一些东西。 ..现在开始寻找...
    【解决方案4】:

    在 php 5.1.3 之前,这家伙已经舔过

    https://macfoo.wordpress.com/2009/06/03/getting-the-root-node-from-an-xml-string

    /**
     * function getXMLRootNode
     * @param string An xml string
     * @return string Return XML root node name
     */
    
    function getXMLRootNode($xmlstr)
    {
     // Create DOM model
     $doc = new DOMDocument();
    
     // Load the XML string
     if(!$doc->loadXML($xmlstr))
     {
     throw new Exception('Unable to parse XML string');
     }
    
     // Find the root tag name
     $root = $doc->documentElement;
    
     if(!isset($root))
     {
     throw new Exception('Unable to find XML root node');
     }
    
     if(!isset($root->nodeName))
     {
     throw new Exception('Unable to find XML root node name');
     }
    
     return $root->nodeName;
    }
    

    在 5.1.3 之前尝试查找如何执行此操作时遇到的交叉发布到 SO 问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-21
      • 1970-01-01
      • 2013-11-26
      相关资源
      最近更新 更多