Is it possible to insert a comment tag into an xml using simplexml?

一曲冷凌霜 提交于 2020-01-10 04:52:10

问题


I am using SimpleXML to build a document, and wondering whether it is possible to insert comment tag to the document like this:

<root>
  <!-- some comment -->
  <value>
</root>

EDIT:

The comment is somewhere in the middle of the document.

<root>
  <tag1 />
  <!-- some comment -->
  <value />
</root>

回答1:


Unfortunately, SimpleXML doesn't handle comments. As it's been mentionned, DOM does handle comments but it's a kind of a bother to use for simple stuff, compared to SimpleXML.

My recommendation: try SimpleDOM. It's an extension to SimpleXML, so everything works the same and it has a bunch of useful methods to deal with DOM stuff.

For instance, insertComment($content, $mode) can append to or insert comments before or after a given node. For example:

include 'SimpleDOM.php';

$root = simpledom_load_string('<root><value/></root>');

$root->value->insertComment(' mode: append ', 'append');
$root->value->insertComment(' mode: before ', 'before');
$root->value->insertComment(' mode: after ', 'after');

echo $root->asPrettyXML();

...will echo

<?xml version="1.0"?>
<root>
  <!-- mode: before -->
  <value>
    <!-- mode: append -->
  </value>
  <!-- mode: after -->
</root>



回答2:


Nope, but apparently you can use DomDocument as a workaround (german):

    $oNodeOld = dom_import_simplexml($oParent);
    $oDom = new DOMDocument();
    $oDataNode = $oDom->appendChild($oDom->createElement($sName));
    $oDataNode->appendChild($oDom->createComment($sValue));
    $oNodeTarget = $oNodeOld->ownerDocument->importNode($oDataNode, true);
    $oNodeOld->appendChild($oNodeTarget);
    return simplexml_import_dom($oNodeTarget);

But then again, why not use DOM directly?




回答3:


There's actually a dirty trick, based on the fact that addChild doesn't check if the element name is valid:

$root->addChild('!-- Your comment --><dummy');

When using $root->asXML() you'd get a string like this:

<root><!-- Your comment --><dummy/></root>

You may notice it generated an empty <dummy> element as well, but it's the price to pay. Don't try to add a value, it would only mess everything up. Use only in conjunction with asXML().

Well, I did say it's a dirty trick. I don't recommend using this in production, but only for debugging/testing purposes.




回答4:


Here is a quick and easy solution:

$xml = new SimpleXMLElement('<root/>');
$xml->element->comment->sample = 12;
$xml_str = $xml->asXML();
$xml_str = str_replace(['<comment>', '</comment>'], ['<!--', '-->'], $xml_str)
echo $xml_str;

<root> <!-- <sample>12</sample> --> </root>


来源:https://stackoverflow.com/questions/2139012/is-it-possible-to-insert-a-comment-tag-into-an-xml-using-simplexml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!