Skip to content
Quasar Tools Logo

How to Comment Out XML Correctly

The complete guide to XML comments: the only valid syntax, where comments are forbidden, how to comment out blocks, and when to strip comments from XML for production.

DH
Tutorials & How-Tos11 min read2,600 words

XML has exactly one comment syntax: the <!-- --> delimiter pair. Unlike YAML or Python, there is no shorthand, no line-level shortcut, and no alternative form. What XML does offer is flexibility — the same delimiter works for single-line notes, multi-paragraph documentation blocks, and temporarily disabling entire sections of markup. This guide covers the full syntax, every location where XML comments are forbidden, the double-hyphen restriction that trips up most developers, and the fastest tools for validating and stripping comments from real-world XML files.

1Comment syntax&lt;!-- --&gt; is the only form
0Lines per commentCan span unlimited lines
100%Parser-discardedComments never reach your app

XML Comment Syntax

An XML comment opens with `<!--` — a less-than sign, an exclamation mark, and two hyphens — and closes with `-->` — two hyphens and a greater-than sign. Every character between those delimiters is the comment content and is completely ignored by every conformant XML parser. The content can include any XML markup, attribute values, text nodes, or processing instructions: none of it is parsed or executed.

The three valid comment forms

All three of the following patterns are correct XML. They differ only in how you choose to lay out the content, not in any meaningful syntax distinction:

  • Inline comment: `&lt;!-- This is a comment --&gt;` — placed on the same line as an element
  • Standalone comment line: `&lt;!-- Full line is a comment --&gt;` — on its own line between elements
  • Multi-line comment block: `&lt;!--` on one line, comment text across several lines, `--&gt;` on the final line

Note

The XML comment syntax is identical in XML 1.0 and XML 1.1, in XHTML, in SVG, and in all XML-based configuration formats like Maven POM files, Spring XML, and Android layout files. The same `<!-- -->` delimiter works everywhere.

What comments look like in the DOM

When an XML parser builds a document tree, comments are represented as Comment nodes — a distinct node type separate from Element, Text, and Attribute nodes. This means library code can access comment nodes if it chooses to, even though they carry no data meaning. Standard DOM traversal methods that iterate child elements skip comment nodes automatically; only explicit comment-node queries return them.

Where XML Comments Are Allowed

XML comments are valid in more positions than most developers expect, but there are a handful of exact locations where the specification forbids them. Understanding these boundaries prevents confusing parse failures that do not mention comments at all in their error messages.

Valid positions

  • Before the root element: comments can appear after the XML declaration and before the first opening tag
  • Between child elements: any whitespace position between sibling elements accepts a comment
  • After the root element: the XML epilog (after the closing root tag) accepts comments and processing instructions
  • Inside element content: a comment placed between a parent tag and its children is valid
  • Between attributes on separate lines: a comment cannot appear inside a tag, but can appear between elements whose attributes span lines

Forbidden positions

Comments are forbidden inside element tags — between the tag name and the closing `>`, inside attribute values, and inside processing instructions. They are also forbidden before the XML declaration itself. Placing `<!-- comment -->` inside an opening tag like `<config <!-- note --> key="value">` is a well-formedness error that every XML parser rejects. The XML declaration `<?xml version="1.0"?>` must also appear before any comment if it appears at all.

LocationExampleValid?
Before root element&lt;!-- doc header --&gt; <root>✓ Yes
Between child elements<a/> &lt;!-- note --&gt; <b/>✓ Yes
After root element</root> &lt;!-- footer --&gt;✓ Yes
Inside element content<p>text &lt;!-- note --&gt; more</p>✓ Yes
Inside an opening tag<elem &lt;!-- note --&gt; attr="v">✗ No — parse error
Inside an attribute value<elem attr="v &lt;!-- note --&gt;">✗ No — literal text
Before XML declaration&lt;!-- note --&gt; <?xml version="1.0"?>✗ No — parse error
Inside a CDATA section<![CDATA[ &lt;!-- not a comment --&gt; ]]>✗ No — literal text

Warning

A common mistake is placing comments inside SVG `<path>` or `<rect>` tags to annotate attribute values. This is invalid XML. Move the comment to a standalone line before or after the element instead.

How to Comment Out XML Blocks Step by Step

Commenting out a block of XML is the most common use of XML comments — temporarily disabling configuration, removing an element during debugging, or preserving an alternative value without deleting it. The process is straightforward, but the double-hyphen restriction adds one extra check you must perform before saving.

1

Place <!-- before the block

Add `<!--` on its own line immediately before the first element you want to disable. Placing it on a separate line keeps the diff clean and makes it easy to identify which lines are commented out in code review. The parser treats everything after the `<!--` as comment content until it finds the matching `-->`.

2

Scan the block for double hyphens

Before adding the closing `-->`, scan every line of the block for any `--` sequence. The XML specification states that `--` is not permitted inside comment content — it terminates the comment early and causes a well-formedness error. Common sources of double hyphens in XML content include SQL snippets in database config files, version numbers like `1.0--beta`, and copied documentation that uses em-dashes encoded as two hyphens.

3

Place --> after the block

Add `-->` on its own line immediately after the last element you want to disable. The parser resumes normal processing from the character after `-->`. If you are commenting out the last element in a document, ensure `-->` appears before the closing root tag — not after it, which would place the comment in the epilog position.

4

Validate the result

Run the modified document through the XML Well-Formedness Checker to confirm the comment is correctly placed and the surrounding document still parses. The checker reports the exact line and column of any well-formedness error introduced by the comment, including the double-hyphen violation if one exists.

XML Well-Formedness Checker

Validate any XML document for parser-level errors — malformed tags, invalid entities, misplaced comments, and double-hyphen violations — with line-level diagnostics in your browser.

Open tool

XML Comment Restrictions and Gotchas

The XML specification imposes three restrictions on comment content that have no equivalent in most other comment systems. Each one causes a specific, identifiable error — and knowing them prevents hours of confused debugging.

The double-hyphen prohibition

The XML 1.0 specification (section 2.5) states: "the string `--` (double-hyphen) must not occur within comments." This means any two adjacent hyphens inside your comment content — regardless of context — will either cause a parse error or terminate the comment at the wrong location, leaving your supposedly-disabled markup live in the document. This rule catches many developers off-guard because `--` is a common sequence in SQL, shell scripts, and CLI option strings that frequently appear in configuration files.

Warning

If you are commenting out a Maven `pom.xml` block that contains a `<!--` comment inside it, the inner `-->` will close your outer comment early, leaving the rest of the inner comment text as unparsed content. XML does not support nested comments. You must remove or replace any `--` sequences inside a block before commenting it out.

Nested comments are forbidden

Unlike some programming languages, XML comments cannot be nested. Attempting to wrap an already-commented block in another `<!-- -->` pair causes the first `-->` inside the block to close the outer comment, leaving the rest as live content. This is the most common comment-related error when working with large configuration files where blocks may already contain documentation comments. The solution is to remove inner comments before applying an outer comment block.

Comments cannot end with a triple hyphen

A related restriction: the comment-closing sequence `-->` must not be preceded by a hyphen, making `--->` invalid. This means a comment like `<!-- note --->` is a well-formedness error. Some lenient parsers accept this silently; strict spec-compliant parsers throw a "malformed comment" error. Always close comments with exactly `-->` and no extra hyphens.

For compatibility, the string `--` (double-hyphen) must not occur within comments. Comments are not part of the document's character data.

XML 1.0 specification, section 2.5

XML Comments by File Type

XML comments appear in dozens of file formats across different ecosystems. The same `<!-- -->` syntax applies everywhere, but the practical use cases and the content patterns that create double-hyphen problems vary by file type.

Maven pom.xml and Gradle build files

Maven POM files are among the most heavily commented XML files in enterprise Java development. Teams use comments to document dependency decisions, explain plugin configuration, and preserve alternative dependency versions for quick switching. The most common problem in POM files is commenting out a `<dependency>` block that already has an XML comment inside it — the inner `-->` closes the outer comment block early. Strip the inner comments before wrapping the block. Use the XML Well-Formedness Checker after editing to confirm the file still parses.

Android layout and manifest files

Android's XML layouts and `AndroidManifest.xml` files follow the same XML comment rules. A common pattern is to comment out an entire `<activity>` or `<uses-permission>` block during development to test different configurations. Because these files are processed by Android's resource compiler before being included in the APK, comments are stripped at build time — they have no runtime impact. Comments cannot appear inside attribute values, so annotating individual attribute settings requires placing the comment on a separate line above the attribute.

SVG files

SVG is an XML vocabulary, so comments use the same `<!-- -->` syntax. They are commonly used to document artboard sections, label layers, and preserve alternative path definitions. SVG comments are preserved when the file is loaded by a browser as an inline `<svg>` or via an `<img>` tag — they appear in the DOM and can be inspected in DevTools. If you are optimising an SVG for production, use the XML Comment Remover to strip comments and reduce file size before deploying.

XSLT stylesheets

XSLT stylesheets are XML documents that transform other XML documents. Comments in XSLT are used to disable template rules during debugging and to document complex XPath expressions. Because XSLT processors execute the stylesheet as XML, a commented-out `<xsl:template>` rule is completely inactive. Pair this with the XPath Finder and Tester to verify your XPath expressions before un-commenting a template rule.


Spring XML configuration

Spring Framework's XML bean configuration files are large, hierarchically structured XML documents where comments are used extensively to document bean scopes, explain dependency injection choices, and preserve legacy configurations. The double-hyphen restriction is particularly relevant in Spring files that reference database connection strings or SQL templates — both frequently contain `--` sequences. Always scan the content before commenting it out and replace any `--` with a single hyphen or a descriptive phrase.

Stripping XML Comments for Production

XML comments intended for developer documentation should not travel to production in all contexts. Stripping them reduces payload size, removes internal notes from publicly accessible feeds, and eliminates the marginal parse overhead of comment nodes in high-throughput XML processing pipelines.

When to strip XML comments

  • RSS and Atom feeds: comments add bytes to publicly accessible feeds without any benefit to feed readers
  • SOAP API payloads: some XML parsers used by enterprise SOAP consumers have strict no-comment policies
  • SVG assets deployed to production: comments increase file size and are visible to anyone inspecting the page source
  • XML configuration files in container images: strip comments to reduce Docker image size and prevent leaking internal documentation
  • XML data files in ETL pipelines: stripping before ingestion reduces parse time and avoids unexpected comment node handling by downstream processors

XML Comment Remover

Strip all XML comments from any document instantly — clean output ready for APIs, deployment, or file size optimisation. Runs entirely in your browser with no uploads.

Open tool

Stripping programmatically

In Python, the `lxml` library provides comment-stripping via `lxml.etree.strip_tags` with the comment type, or you can iterate all comment nodes and call `remove()`. The standard `xml.etree.ElementTree` library discards comments by default when parsing — they do not appear in the element tree at all. In Node.js, the `fast-xml-parser` library ignores comments during parsing, and the `xml2js` library does the same with the default configuration. For a quick no-code approach, the XML Comment Remover handles any XML document in your browser without requiring any library setup.

Note

Comment stripping is a lossless operation on the data side. The parsed XML object is semantically identical before and after removing comments. Always keep the commented source version under version control and strip only for the deployed artifact.

XML Comment Best Practices

Well-structured XML comments make configuration files significantly easier to maintain, review, and hand off. These patterns appear across Maven POM files, Spring XML configs, SVG assets, and Android manifests in professional codebases.

Document intent, not mechanics

A comment that restates what an element does adds no value. A comment that explains why the element is configured that way is genuinely useful. In a Maven POM, a comment like `<!-- Pinned to 3.2.1 because 3.3.0 broke transaction rollback on Oracle 19c -->` tells the next developer exactly what they need to know before upgrading the dependency. The raw version number alone does not.

Keep comments short and above, not beside

XML elements frequently have long attribute lists that span multiple lines. An inline comment placed after an attribute makes the line even longer and breaks formatting. The standard convention in XML files is to place explanatory comments on a dedicated line above the element they describe, not on the same line. This also ensures the comment is valid — recall that comments inside tags are forbidden regardless of line length.

  • Good: comment on its own line above the element — `&lt;!-- Required for SSO login flow --&gt;\n&lt;property name="authProvider" value="saml"/&gt;`
  • Avoid: comment after an attribute on the same tag line — causes a well-formedness error
  • Good: section separator comments — `&lt;!-- ═══ Database Configuration ═══ --&gt;` before a logical group of beans
  • Avoid: commented-out code left in files indefinitely — archive it in version control instead of keeping dead markup
  • Good: removing `--` sequences from commented-out code before committing — prevents future well-formedness errors

Tip

Before committing any XML file with new comments, run it through the [XML Well-Formedness Checker](/tools/data/validators/xml-well-formedness-checker). The check completes in under a second and catches double-hyphen violations, misplaced comment positions, and any structural errors introduced while adding the comments.

Validate after converting to or from other formats

If you convert a JSON or YAML config to XML using the XML to JSON Converter or a similar tool, the output will not carry comments from the source — JSON and YAML comments are not preserved in the conversion. Add any XML documentation comments manually after conversion, then validate the result. Conversely, if you convert XML to YAML, comments are dropped because the converter reads the parsed DOM tree, not the raw source text. Keep the original XML as the authoritative source when documentation comments are important.

Key takeaways

  • XML has exactly one comment syntax: `&lt;!-- comment --&gt;`. There are no alternative forms.
  • Comments cannot appear inside element opening or closing tags, inside attribute values, or before the XML declaration.
  • The `--` (double-hyphen) sequence is forbidden inside XML comment content — it terminates the comment early and causes a well-formedness error.
  • XML comments cannot be nested — the first `--&gt;` inside a block always closes the outermost open comment.
  • Use the XML Well-Formedness Checker after adding comments to catch double-hyphen violations and misplaced comment positions.
  • Strip comments before deploying to production using the XML Comment Remover — comments are preserved in the source but add no value to deployed artifacts.
  • Place comments on their own lines above the elements they describe — never inside a tag or after an attribute value on the same line.

Frequently Asked Questions

The only valid XML comment syntax is <!-- comment text -->. The opening delimiter is <!-- (less-than, exclamation mark, two hyphens) and the closing delimiter is --> (two hyphens, greater-than). Everything between the delimiters is the comment content and is ignored by the XML parser. There are no other comment syntaxes in XML — no // single-line comments, no # hash comments, and no /* */ block delimiters.

No. XML comments cannot appear inside element tags, attribute names, or attribute values. The comment delimiters <!-- and --> are only valid outside of tags — between elements, before the root element, or after the root element. Placing <!-- inside an opening tag like <element <!-- comment --> attr="value"> is a well-formedness error that any XML parser will reject.

Yes. An XML comment can span as many lines as needed. The opening <!-- and closing --> delimiters define the start and end regardless of how many line breaks appear between them. This is the standard way to comment out a large block of XML — place <!-- before the block on its own line and --> after the block on its own line. The entire content between the delimiters, including newlines, is ignored by the parser.

The most common cause is a double hyphen sequence (--) inside the comment content. The XML specification prohibits -- inside a comment because it would be ambiguous with the --> closing delimiter. If your comment text contains an em-dash, a decrement operator (-- in C or SQL), or any two adjacent hyphens, the parser treats them as the start of the closing sequence and either errors or terminates the comment at the wrong location. Replace -- with a single hyphen or rephrase the text.

Yes, using the same <!-- --> syntax. XSLT stylesheets are valid XML documents, so the same comment rules apply. You can comment out entire <xsl:template> blocks, individual <xsl:apply-templates> instructions, or any other XSLT elements using XML comment syntax. Note that XSLT processors do not execute commented-out templates — commenting is an effective way to disable a transformation rule during debugging without deleting it.

No. The XML declaration (<?xml version="1.0" encoding="UTF-8"?>) must be the very first thing in an XML document if it is present. A comment placed before the XML declaration is a well-formedness error. Comments are valid after the XML declaration, before the root element, between elements, and after the root element — but never before the declaration.

In Python, load the document with the standard xml.etree.ElementTree library — it discards comments by default when parsing. To strip them explicitly with lxml, iterate comment nodes and remove them before serialising. In JavaScript or Node.js, the DOMParser API ignores comments when parsing to a DOM, but you can also use a simple regex for processing pipelines. For a no-code option, the Quasar Tools XML Comment Remover strips all comment nodes from any XML document instantly in your browser.

Yes, but with subtle differences. HTML browsers use the same <!-- --> syntax for comments, but the HTML parser is more lenient — it allows -- inside comments in most HTML5 parsers, which would be a well-formedness error in strict XML. If your document is served as application/xml or text/xml (XHTML), the strict XML rules apply and -- inside comments will cause a parse failure. For HTML served as text/html, the HTML5 rules apply and most browsers tolerate double hyphens inside comments.

ShareXLinkedIn

Related articles