php 确定 DOMElement 的父节点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:14:17  来源:igfitidea点击:

Determine Parent Node Of DOMElement

phpxmldom

提问by user2601

I'm translating my C# code for YouTube video comments into PHP. In order to properly nest comment replies, I need to re-arrange XML nodes. In PHP I'm using DOMDocument and DOMXPath which closely corresponds to C# XmlDocument. I've gotten pretty far in my translation but now I'm stuck on getting the parent node of a DOMElement. A DOMElement does not have a parent_node() property, only a DOMNode provides that property.

我正在将 YouTube 视频评论的 C# 代码翻译成 PHP。为了正确嵌套评论回复,我需要重新排列 XML 节点。在 PHP 中,我使用 DOMDocument 和 DOMXPath,它们与 C# XmlDocument 密切对应。我的翻译已经走得很远了,但现在我坚持获取 DOMElement 的父节点。DOMElement 没有 parent_node() 属性,只有 DOMNode 提供该属性。

After determining that a comment is a reply to a previous comment based in the string "in-reply-to" in a link element, I need to get its parent node in order to nest it beneath the comment it is in reply to:

在确定评论是对基于链接元素中的字符串“in-reply-to”的先前评论的回复后,我需要获取其父节点以便将其嵌套在其回复的评论下方:

// Get the parent entry node of this link element
$importnode = $objReplyXML->importNode($link->parent_node(), true);

回答by Marius

DOMElementis a subclass of DOMNode, so it does have parent_node property. Just use $domNode->parentNode; to find the parent node.

DOMElementDOMNode的子类,因此它确实具有 parent_node 属性。只需使用 $domNode->parentNode; 找到父节点。

In your example, the parent node of $importnode is null, because it has been imported into the document, and therefore does not have a parent yet. You need to attach it to another element before it has a parent.

在您的示例中, $importnode 的父节点为空,因为它已导入到文档中,因此还没有父节点。你需要在它有父元素之前将它附加到另一个元素。

回答by Marius

I'm not entirely sure how your code works, but it seems like you have a small error in your code.

我不完全确定您的代码是如何工作的,但您的代码中似乎有一个小错误。

On the line you posted in your question you have $link->parent_node(), but in the answer with the entire code snippet you have $link**s**->parent_node().

在您发布在您的问题中的行中$link->parent_node(),但在您拥有的整个代码片段的答案中$link**s**->parent_node()

I don't think the sshould be there.

我不认为s应该在那里。

Also, I think you should use $link->parentNode, not $link->parent_node().

另外,我认为您应该使用 $link->parentNode,而不是 $link->parent_node()。

回答by Dimas Lanjaka

Replace parent_node()to parentNode

替换parent_node()parentNode