将节点分配给任意节点,如何使用Libxml2? [英] Assigning a node to an arbitrary node, how to with Libxml2?

查看:59
本文介绍了将节点分配给任意节点,如何使用Libxml2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题使用PHP,但问题和算法对许多其他 Libxml2和W3C DOM 实现有效。

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

核心问题:没有 $ node-&replaceThisBy($ otherNode) 。只有替换文字(使用 nodeValue 属性)和 replaceChild()方法—

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.

在下面的代码中,仅第二个循环有效,但是我需要将节点从一棵DOM树(由克隆模拟)复制到另一棵

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:

  • PHP DOM replace element with a new element
  • PHP DOMDocument question: how to replace text of a node?

推荐答案

nodeValue 属性,仅更改文本值。要更改所有标签和内容,需要更多说明- DomDocument 不友好(!)...需要导入克隆,然后在循环中克隆:已解决!

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();

这篇关于将节点分配给任意节点,如何使用Libxml2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆