【问题标题】:Commenting and Un-Commenting a Node in an XML Document在 XML 文档中注释和取消注释节点
【发布时间】:2012-12-08 10:41:30
【问题描述】:
<node1>
    <node2>
         <node3>
         </node3>
         <node3>
         </node3>
         <node3>
         </node3>
    </node2>

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

    ...
 </node1>

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

编辑:澄清一下:我找到了如何评论节点,但没有找到如何取消评论。

【问题讨论】:

    标签: php xml domdocument


    【解决方案1】:

    可以使用DOMDocument::createComment() 创建评论。用实际节点替换 cmets 就像替换任何其他节点类型一样,使用 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>
    

    参考

    【讨论】:

    • 你太棒了。感谢您的宝贵时间,我会仔细研究这些方法。
    猜你喜欢
    • 1970-01-01
    • 2015-09-19
    • 1970-01-01
    • 2018-05-07
    • 2016-12-10
    • 2020-12-30
    • 2021-08-04
    相关资源
    最近更新 更多