php - Assigning a node to an arbitrary node, how to with Libxml2? -
this question use php, problems , algorithms valid many other libxml2 , w3c dom implementations.
core problem: there no $node->replacethisby($othernode)
. there "replace text" (using nodevalue
property) , replacechild()
method — not obviuos neither simple use.
in code below, second loop works, need copy nodes 1 dom tree (simulated clone) one.
$doc = new domdocument('1.0', 'utf-8'); $doc->load($filexml); $xp = new domxpath($doc); $lst = $xp->query("//td"); $z = clone $lst->item(2); // big , complex node // needs clone freeze node content (before change also). // not work: foreach ($lst $node) $node = $z; // no error messages! //error: $node->parentnode->replacechild($z,$node); // works though: foreach ($lst $node) $node->nodevalue = $z->nodevalue;
similar questions:
nodevalue property, changes text-value. change tags , contents, need lot more instructions -- domdocument not friendly (!) ... need import clone, , clone in 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 $node) { $tmp = clone $import; // clone because if same, ignores loop. $node->parentnode->replacechild($tmp,$node); } print $doc->savexml();
Comments
Post a Comment