Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

xml

simplexml

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>
like image 304
pihentagy Avatar asked Jan 26 '10 11:01

pihentagy


People also ask

How do you put a comment in an XML file?

An XML comment encountered outside the document type declaration is represented by the Comment value syntax element. It contains the comment text from the XML message. If the value of the element contains the character sequence --> , the sequence is replaced with the text --&gt; .

Does XML allow commenting elements?

Allows notes and other human readable comments to be included within an XML file. XML Parsers should ignore XML comments. Some constrains govern where comments may be placed with an XML file.

How do you comment a line in POM XML?

Rather than just commenting out a single line, you may need to comment out a whole section of your XML code. To do this, insert your cursor on a blank line above the section of XML code you want to comment out and then type a less-than symbol followed by an exclamation point and two dashes.

Can XML comments be nested?

XML comment sections cannot be nested, because content cannot contain the value "-->".


1 Answers

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>
like image 139
Josh Davis Avatar answered Oct 24 '22 06:10

Josh Davis