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.
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: `<!-- This is a comment -->` — placed on the same line as an element
- Standalone comment line: `<!-- Full line is a comment -->` — on its own line between elements
- Multi-line comment block: `<!--` on one line, comment text across several lines, `-->` on the final line
Note
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.
| Location | Example | Valid? |
|---|---|---|
| Before root element | <!-- doc header --> <root> | ✓ Yes |
| Between child elements | <a/> <!-- note --> <b/> | ✓ Yes |
| After root element | </root> <!-- footer --> | ✓ Yes |
| Inside element content | <p>text <!-- note --> more</p> | ✓ Yes |
| Inside an opening tag | <elem <!-- note --> attr="v"> | ✗ No — parse error |
| Inside an attribute value | <elem attr="v <!-- note -->"> | ✗ No — literal text |
| Before XML declaration | <!-- note --> <?xml version="1.0"?> | ✗ No — parse error |
| Inside a CDATA section | <![CDATA[ <!-- not a comment --> ]]> | ✗ No — literal text |
Warning
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.
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 `-->`.
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.
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.
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.
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
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 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.
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
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 — `<!-- Required for SSO login flow -->\n<property name="authProvider" value="saml"/>`
- Avoid: comment after an attribute on the same tag line — causes a well-formedness error
- Good: section separator comments — `<!-- ═══ Database Configuration ═══ -->` 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
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: `<!-- comment -->`. 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 `-->` 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.