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:
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!