注释和取消注释XML文档中的节点 [英] Commenting and Un-Commenting a Node in an XML Document

查看:51
本文介绍了注释和取消注释XML文档中的节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

    ...
 </node1>

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

编辑:只是澄清一下:我知道如何注释节点,但不知道如何取消注释。

推荐答案

评论可以使用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>

参考资料

这篇关于注释和取消注释XML文档中的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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