2

I am getting following error while Traversing DOM in PHP

Fatal error: Call to undefined method DOMText::getAttribute()

What I am doing is, I am traversing DOM Nodes one-by-one. But in some cases I am not getting Proper DOM node like from which I can get specific Attribute. As I am getting DOMText Node, ->nodeType==3 always (not DOM Node, ->nodeType == 1), hence I am not able to fetch any Attribute of returned DOM Node.

I am fetching Next DOM Node using below syntax in PHP

$node = $node->nextSibling;

and in some cases I also require to fetch Previous Nodes as well like this

$node = $node->previousSibling;

Now, my question is, How can I get proper DOM Node?

I have tried below function

function GetNode($oNode)
{
    while($oNode->nodeType != 1)
        $oNode = $oNode->previousSibling;
    return $oNode;
}

with checking condition (where I have used that Node) like

while($node && !empty($node) && $node->nodeType == 1 && !preg_match("/^Abc/",$node->getAttribute('class')))
{
    //further code
    $node = $node->nextSibling;
    $node = GetNode($node);
}

But now problem occurs that it goes in infinite loop because it's returning always nodeType == 1 and does not terminating loop.

4

1 回答 1

4

文本节点和其他任何一个 dom 元素一样。它出现是因为您的 xml 中的标签之间有纯文本(例如换行符)。所以你应该只检查 nodeType 并跳过文本节点。

在您的代码中,“GetNode”函数存在错误:您应该使用 $oNode->nextSibling 而不是 $oNode->previousSibling。

PS 现代浏览器具有跳过文本节点的 .nextElementSibling 属性;)

于 2013-08-03T21:45:57.330 回答