Is it possible to insert a comment tag into an xml

2019-01-27 23:46发布

问题:

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>