How to Format Comments in an XML Document
Comments in XML are used to leave explanatory notes, document the structure of data, or temporarily disable code without affecting how the document is parsed. This guide explains the correct syntax for single-line and multi-line XML comments, outlines critical syntax rules to avoid parser errors, and provides practical examples of proper usage.
Basic Syntax for XML Comments
XML comments begin with the opening sequence <!-- and
end with the closing sequence -->. Any text placed
between these markers is ignored by the XML parser.
<!-- This is a standard XML comment -->
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>Multi-Line Comments
You can write comments that span multiple lines using the exact same opening and closing tags. Line breaks and whitespace inside the comment are ignored by the parser.
<!--
This is a multi-line comment.
It can span as many lines as necessary
to explain complex data structures.
-->
<user id="101">
<name>Alex</name>
</user>Rules for Writing XML Comments
To ensure your XML document remains well-formed and valid, you must follow these syntax rules:
- No Nested Comments: You cannot place a comment
inside another comment. An opening tag cannot be followed by another
opening tag before the first is closed.
- Incorrect:
<!-- Outer comment <!-- Inner comment --> -->
- Incorrect:
- Avoid Double Hyphens Inside Comments: The sequence
--must not appear anywhere inside the comment body, as parsers interpret double hyphens as part of the closing sequence.- Incorrect:
<!-- Check the value -- it should be valid --> - Correct:
<!-- Check the value - it should be valid -->
- Incorrect:
- Cannot Be Placed Inside Tags: Comments cannot be
embedded within markup tags or attribute definitions.
- Incorrect:
<user <!-- comment --> id="101"> - Correct:
<!-- User ID attribute --> <user id="101">
- Incorrect:
- Cannot Precede the XML Declaration: If your
document includes an XML declaration
(
<?xml version="1.0"?>), it must strictly be the first line of the file. Comments cannot appear before it.