【问题标题】:DOMDocument How to Append to newly Appended Child Element in createDocumentFragment?DOMDocument 如何追加到createDocumentFragment 中新追加的子元素?
【发布时间】:2020-08-04 18:40:46
【问题描述】:

您好,我想知道如何在新创建的附加子节点中附加 XML 标记?

这就是我所拥有的,

$newNode = $xml->createDocumentFragment();
$reCreateOldNode = $xml->createElement("myNewChild");
$newNode->appendChild($reCreateOldNode);         // This is Newly Appended Child
   while ($node->firstChild) {
     $match->nodeValue = "";
     $newNode->appendChild($node->firstChild);
     $newNode->appendXML($actionOutput);        // I want to Append the XML to $newNode->myNewChild
   }
$node->parentNode->replaceChild($newNode, $node);

这是新创建的 Child,

$newNode->appendChild($reCreateOldNode);  

我想将我创建的 XML 直接附加到 $newNode->myNewChild 而不是 $newNode

【问题讨论】:

  • 你的意思是像$appendNode = $newNode->appendChild($reCreateOldNode); 然后将新节点添加到$appendNode(再次使用appendChild())。
  • 我使用 github.com/nullivex/lib-array2xml 来简化我的 xml 工作流程,说我一直使用 appendXML 而不是 appendChild
  • @NigelRen 在附加子 $reCreateOldNode 后,我想附加一个 appendXML 而不是 appendChild,因为我只准备了 XML 标签,但是当我尝试将 XML 附加到 $newNode 时,我得到未定义的函数 appendXML
  • 当您已经操作 DOM 本身时,自己创建 XML 似乎是一个奇怪的想法。 (它也可能容易出错)。 stackoverflow.com/questions/31144422/… 可能会有所帮助 - 它基本上是导入 XML,然后处理附加内容。

标签: php xml domdocument


【解决方案1】:

文档片段的实际目的是允许您将节点列表(元素、文本节点、cmets...)视为单个节点,并将它们用作 DOM 方法的参数。您只想附加一个节点(及其后代) - 无需将此节点附加到片段。

在 PHP 中,文档片段可以解析 XML 片段字符串。因此,您可以使用它将字符串解析为 XML sn-p,然后将其附加到 DOM 节点。此片段将附加到新节点。

$document = new DOMDocument();
$document->loadXML('<old>sample<foo/></old>');
$node = $document->documentElement;

// create the new element and store it in a variable
$newNode = $document->createElement('new');
// move over all the children from "old" $node
while ($childNode = $node->firstChild) {
    $newNode->appendChild($childNode);
}

// create the fragment for the XML snippet
$fragment = $document->createDocumentFragment();
$fragment->appendXML('<tag/>text');

// append the nodes from the snippet to the new element
$newNode->appendChild($fragment);

$node->parentNode->replaceChild($newNode, $node);

echo $document->saveXML();

输出:

<?xml version="1.0"?>
<new>sample<foo/><tag/>text</new>

【讨论】:

    猜你喜欢
    • 2012-03-05
    • 2015-02-04
    • 2014-04-17
    • 2022-11-21
    • 2023-03-09
    • 1970-01-01
    • 2011-11-10
    • 1970-01-01
    • 2017-08-24
    相关资源
    最近更新 更多