Why XML Comments Are Not Allowed Inside Tags

This article explains why the XML specification prohibits placing comments directly inside opening, closing, or empty-element tags. By examining the formal grammar defined by the World Wide Web Consortium (W3C), lexical tokenization, and design goals of XML, you will understand the technical constraints that keep XML parsers fast, deterministic, and unambiguous.

The W3C XML Grammar Definition

According to the official W3C XML specification, elements must follow a rigid syntactic structure. The grammar for a start-tag is formally defined as:

STag ::= '<' Name (S Attribute)* S? '>'
EmptyElemTag ::= '<' Name (S Attribute)* S? '/>'

In these rules, Name represents the tag name, and S represents standard whitespace characters (spaces, tabs, line breaks). The grammar explicitly allows only attributes and whitespace between the tag name and the closing delimiter (> or />).

The rule for a comment (<!-- ... -->) is defined separately in the specification’s content model, which means it can only appear within the general markup of the document, between elements, or alongside the root element—never inside tag delimiters.

Parser Simplicity and Performance

A primary design goal of XML was to create a streamlined subset of SGML that is easy to implement and process. In SGML, complex comment-nesting rules caused parsing overhead and implementation discrepancies across different platforms.

By strictly excluding comments from inside tags, XML parsers do not need to switch lexer states or track nested comment delimiters while processing element names and attributes. The parser can simply scan linearly from < to > to process attributes without accounting for arbitrary comment boundaries.

Elimination of Lexical Ambiguity

Permitting comments within tags introduces edge cases that increase the likelihood of parsing errors. For example:

To avoid these ambiguities, the XML specification enforces a strict separation: tags define structure and attributes, while comments provide human-readable metadata outside of structural tokens.

Proper Placement of XML Comments

To comment on specific attributes or element structures without causing validation errors, comments must always be placed outside the tag itself:

<!-- Configure the active connection timeout in seconds -->
<connection timeout="60" />

Placing the comment inside the tag (such as <connection <!-- timeout in seconds --> timeout="60" />) violates XML well-formedness rules and causes conforming XML parsers to immediately halt execution with a fatal syntax error.