tags:

views:

137

answers:

3

Is there any way to retrieve the comments from an XML file?

I have an XML file, with comments in it, and i have to build an user-interface based on each node in this file, and the associated comments.

I can't seem to find a way to get those comments. I was able to get 'some' of them using simpleXML, but it didn't work for the root node, and was acting pretty strange... some comments wre put in their own node, some other were left as childs, and all comments were put in the same node... Not sure this makes any sense:) the point is simpleXML broke the structure of the comments and it wasn't good for my needs.

A: 

simpleXml is good for quick grabbing of something, but it has limitations. Use The DOM parser instead. Or in this case, perhaps an event-based one (SAX or XmlReader).

troelskn
i used the class from http://www.php.net/manual/en/function.xml-parse.php#86312 and it dosent seem to see the comment nodes. I'll try to play around with the DOM parser
Quamis
+2  A: 

You can use XMLReader to read through all of the nodes and pull out the comments. I've included some sample code to get you started, as it just pulls out the nodes, and doesn't take into account where the comment is inside, below or above any xml nodes.

$comments = '';
$xml =<<<EOX
<xml>
    <!--data here -->
    <data>
        <!-- more here -->
        <more />
    </data>
</xml>
EOX;

$reader = new XMLReader();
$reader->XML($xml);

while ($reader->read()) {
  if ($reader->nodeType == XMLReader::COMMENT) {
      $comments .= "\n".$reader->value;
  }
}

$reader->close();

echo "all comments below:\n-------------------".$comments

The expected output is:

all comments below:
-------------------
 data here
 more here

So just the values of the comments (not the <!-- -->) will be taken, as well as whitespace.

null
thx, i'll give it a try tommorow, but it looks pretty straightforward:)
Quamis
A: 

It's simple if you use XPath. The comment() function matches comments. So the pattern

//comment()

finds all comments in the document.

In XSLT, for the general pattern where the comment precedes the element you're transforming, e.g.:

<!-- This is the comment -->
<element>...

you'd use a template like:

<xsl:template match="*[.::preceding-sibling()/comment()]">
   <xsl:variable name="comment" select=".::preceding-sibling()/comment()"/>
   <!-- xsl:value-of $comment will now give you the text of the comment -->
   ...
Robert Rossney