Assigning a node to an arbitrary node, how to with

2019-09-05 17:51发布

This question use PHP, but the problems and algorithms are valid for many other Libxml2 and W3C DOM implementations.

Core problem: there are no $node->replaceThisBy($otherNode). There are only "replace text" (using nodeValue property) and the replaceChild() method — not obviuos neither simple to use.

In the code below, only the second loop works, but I need copy nodes from one DOM tree (simulated by a clone) to another one.

$doc = new DOMDocument('1.0', 'UTF-8');
$doc->load($fileXML);
$xp = new DOMXpath($doc);
$lst = $xp->query("//td");

$z =  clone $lst->item(2);   // a big and complex node
         // needs clone to freeze the node content (before change it also). 
// does NOT work:
foreach ($lst as $node)
    $node = $z;  // no error messages!
    //error: $node->parentNode->replaceChild($z,$node);

// This works though:
foreach ($lst as $node)
    $node->nodeValue = $z->nodeValue;

Similar questions:

1条回答
Lonely孤独者°
2楼-- · 2019-09-05 18:37

nodeValue property, changes only text-value. To change all tags and contents, need a lot more instructions -- DomDocument is not friendly (!) ... Need to import a clone, and clone in the loop: solved!

  $doc = new DOMDocument('1.0', 'UTF-8');
  $doc->loadXML($xmlFrag);

  $xp = new DOMXpath($doc);
  $lst = $xp->query("//p");
  $import = $doc->importNode( $lst->item(1)->cloneNode(true) , TRUE);

  foreach ($lst as $node) {
    $tmp = clone $import; // clone because if same, ignores loop.
    $node->parentNode->replaceChild($tmp,$node);
  }
  print $doc->saveXML();
查看更多
登录 后发表回答