2012-12-20 61 views
1
<node1> 
    <node2> 
     <node3> 
     </node3> 
     <node3> 
     </node3> 
     <node3> 
     </node3> 
    </node2> 

    <node2> 
     <node3> 
     </node3> 
     <node3> 
     </node3> 
     <node3> 
     </node3> 
    </node2> 

    ... 
</node1> 

假设我在XML文档中具有此结构。我希望能够评论一个节点及其所有内容,并在取消注释,如有必要,使用PHP。我试图找到一种方法来查看DOMDocument的文档和SimpleXML的文档,但没有成功。注释和取消注释XML文档中的节点

编辑:只是澄清:我发现如何评论一个节点,但不知道如何取消它的评论。

+0

的内容告诉我们你的php – valentinas

回答

2

评论可使用DOMDocument::createComment()创建。使用实际节点替换注释就像替换任何其他节点类型一样,请使用DOMElement::replaceChild()

$doc = new DOMDocument; 
$doc->loadXML('<?xml version="1.0"?> 
<example> 
    <a> 
     <aardvark/> 
     <adder/> 
     <alligator/> 
    </a> 
</example> 
'); 

$node = $doc->getElementsByTagName('a')->item(0); 

// Comment by making a comment node from target node's outer XML 
$comment = $doc->createComment($doc->saveXML($node)); 
$node->parentNode->replaceChild($comment, $node); 
echo $doc->saveXML(); 

// Uncomment by replacing the comment with a document fragment 
$fragment = $doc->createDocumentFragment(); 
$fragment->appendXML($comment->textContent); 
$comment->parentNode->replaceChild($fragment, $comment); 
echo $doc->saveXML(); 

的(超级简化)上面的例子应该输出类似:

<?xml version="1.0"?> 
<example> 
    <!--<a> 
     <aardvark/> 
     <adder/> 
     <alligator/> 
    </a>--> 
</example> 
<?xml version="1.0"?> 
<example> 
    <a> 
     <aardvark/> 
     <adder/> 
     <alligator/> 
    </a> 
</example> 

参考

+0

你真了不起。谢谢你的时间,我会仔细研究这些方法。 –

+0

+1:非常好的答案。 – hakre