3.5 Comments

Comments are an XML construction, and are normally only valid inside a DTD. However, as Section 3.4 shows, it is possible to use XML syntax within your document.

The delimiter for XML comments is the string “--”. The first occurrence of this string opens a comment, and the second closes it.

Example 3-8. XML Generic Comment

<!-- test comment -->

<!-- This is inside the comment -->

<!-- This is another comment    -->

<!-- This is one way
     of doing multiline comments -->

<!-- This is another way of   --
  -- doing multiline comments -->

If you have used XHTML before you may have been shown different rules for comments. In particular, you may think that the string <!-- opens a comment, and it is only closed by -->.

This is not the case. A lot of web browsers have broken XHTML parsers, and will accept that as valid. However, the XML parsers used by the Documentation Project are much stricter, and will reject documents that make that error.

Example 3-9. Erroneous XML Comments


<!-- This is in the comment --

     THIS IS OUTSIDE THE COMMENT!

  -- back inside the comment -->

The XML parser will treat this as though it were actually:

<!THIS IS OUTSIDE THE COMMENT>

This is not valid XML, and may give confusing error messages.

<!--------------- This is a very bad idea --------------->

As the example suggests, do not write comments like that.

<!--===================================================-->

That is a (slightly) better approach, but it still potentially confusing to people new to XML.

3.5.1 For You to Do…

  1. Add some comments to example.xml, and check that the file still validates using xmllint.

  2. Add some invalid comments to example.xml, and see the error messages that xmllint gives when it encounters an invalid comment.