← Back to XML Articles

XML Comments: Syntax & Best Practices

Complete guide to writing effective XML comments with syntax, examples, and professional best practices

Documentation8 min read

XML comments allow you to add notes, explanations, and documentation to your XML documents without affecting the data. Comments are ignored by XML parsers and don't appear in the processed output.

This guide covers everything you need to know about XML comments, from basic syntax to advanced best practices used by professional developers.

XML Comment Syntax

Basic Syntax

XML comments start with <!-- and end with -->

<!-- This is an XML comment -->
XML
<?xml version="1.0" encoding="UTF-8"?>
<!-- This is a comment in XML -->
<catalog>
  <!-- Product catalog starts here -->
  <product id="101">
    <name>Laptop</name>
    <!-- Price in USD -->
    <price>999.99</price>
  </product>
  <!-- More products below -->
</catalog>

Comment Examples

1. Section Headers

Use comments to mark sections in large XML files:

XML
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  
  <!-- ========================================
       DATABASE CONFIGURATION
       ======================================== -->
  <database>
    <host>localhost</host>
    <port>3306</port>
  </database>
  
  <!-- ========================================
       EMAIL SETTINGS
       ======================================== -->
  <email>
    <smtp>smtp.example.com</smtp>
    <port>587</port>
  </email>
  
</configuration>

2. Inline Documentation

Explain specific elements or attributes:

XML
<user id="123">
  <!-- Username must be unique across system -->
  <username>john_doe</username>
  
  <!-- Email used for password recovery -->
  <email>[email protected]</email>
  
  <!-- Status: active, inactive, suspended -->
  <status>active</status>
</user>

3. Temporarily Disable Elements

Comment out elements during testing or debugging:

XML
<features>
  <feature name="dark-mode" enabled="true" />
  <feature name="notifications" enabled="true" />
  
  <!-- Temporarily disabled for testing
  <feature name="analytics" enabled="true" />
  -->
  
  <feature name="caching" enabled="true" />
</features>

4. Version History & Change Log

Document changes to your XML structure:

XML
<?xml version="1.0" encoding="UTF-8"?>
<!--
  File: config.xml
  Version: 2.1.0
  Last Modified: 2025-01-15
  Author: Development Team
  
  Change Log:
  - v2.1.0 (2025-01-15): Added cache settings
  - v2.0.0 (2024-12-01): Restructured database config
  - v1.0.0 (2024-06-01): Initial release
-->
<configuration>
  <settings>
    <!-- Configuration content -->
  </settings>
</configuration>

Multi-Line Comments

XML comments can span multiple lines, making them perfect for detailed documentation:

XML
<?xml version="1.0" encoding="UTF-8"?>
<!--
  API Configuration File
  
  This file contains all configuration settings for the API service.
  
  Important Notes:
  - All endpoints require authentication
  - Rate limiting is enabled by default
  - Timeout values are in milliseconds
  - Contact [email protected] for production credentials
  
  DO NOT commit with production credentials!
-->
<api-config>
  <endpoint>https://api.example.com</endpoint>
  
  <!--
    Authentication settings
    Supported types: basic, bearer, oauth2
  -->
  <auth type="bearer">
    <token>YOUR_TOKEN_HERE</token>
  </auth>
  
  <!--
    Rate limiting configuration
    Max requests per minute per IP address
  -->
  <rate-limit>100</rate-limit>
</api-config>

Nested Comments (Not Allowed)

⚠Important: Comments Cannot Be Nested

XML does not support nested comments. You cannot put a comment inside another comment.

❌ INVALID (Won't Work):

XML
<!-- Outer comment
  <user>
    <!-- Inner comment -->
    <name>John</name>
  </user>
-->

This will cause a parsing error!

✓ VALID (Use Separate Comments):

XML
<!-- Start of section -->
<user>
  <!-- Name field -->
  <name>John</name>
</user>
<!-- End of section -->

Separate comments work perfectly!

Best Practices

Be Clear and Concise

Write comments that explain WHY, not what. The XML structure shows what.

Good:

<!-- Cache expires after 5 minutes to balance freshness and performance -->

Bad:

<!-- This is the cache expiry value -->

Keep Comments Updated

Outdated comments are worse than no comments. Update them when code changes.

Use Consistent Formatting

Maintain a consistent comment style across your XML documents.

Avoid Redundant Comments

Don't comment on self-explanatory elements. Comment on complex logic or business rules.

Document Business Rules

Explain business logic, validation rules, or constraints that aren't obvious from the structure.

Use TODO Comments

Mark incomplete sections or future improvements with TODO comments.

<!-- TODO: Add validation for email format -->

Common Mistakes to Avoid

❌ Using Double Dashes Inside Comments

The sequence -- cannot appear inside XML comments except at the end.

INVALID:

<!-- This is a test--comment -->

VALID:

<!-- This is a test comment -->

❌ Commenting Out Comments

You cannot nest comments in XML. Remove inner comments first.

❌ Using Comments Before XML Declaration

Comments must come AFTER the <?xml?> declaration.

INVALID:

XML
<!-- Comment -->
<?xml version="1.0"?>
<root />

VALID:

XML
<?xml version="1.0"?>
<!-- Comment -->
<root />

❌ Storing Data in Comments

Never use comments to store data. Comments are ignored by parsers and may be stripped.

❌ Leaving Sensitive Information

Don't put passwords, API keys, or sensitive data in comments, even temporarily.

When to Use XML Comments

✓ Good Use Cases

  • • Documenting file purpose and version
  • • Explaining business rules
  • • Section headers in large files
  • • Temporarily disabling elements
  • • TODO and FIXME notes
  • • Configuration instructions
  • • Complex transformation logic
  • • Validation rules explanation

❌ Avoid Comments For

  • • Self-explanatory elements
  • • Storing actual data
  • • Version control (use Git)
  • • Long-term element disabling
  • • Sensitive information
  • • Debugging output (use tools)
  • • Obvious structure explanations
  • • Metadata (use attributes instead)

Real-World Example

Here's a professionally commented XML configuration file:

XML
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ================================================
  E-Commerce Platform Configuration
  ================================================
  Version: 3.2.1
  Environment: Production
  Last Updated: 2025-01-15
  
  Contact: [email protected]
  Documentation: https://docs.example.com/config
  ================================================
-->
<ecommerce-config>
  
  <!-- 
    Payment Gateway Configuration
    Current provider: Stripe
    Fallback to PayPal if Stripe fails
  -->
  <payment>
    <gateway name="stripe">
      <!-- Public key only - secret in environment vars -->
      <public-key>pk_live_xxxxx</public-key>
      <!-- Timeout in seconds -->
      <timeout>30</timeout>
    </gateway>
    
    <!-- Fallback gateway -->
    <gateway name="paypal" fallback="true">
      <client-id>xxxxx</client-id>
      <timeout>30</timeout>
    </gateway>
  </payment>
  
  <!--
    Inventory Management
    Auto-restock when quantity falls below threshold
  -->
  <inventory>
    <!-- Minimum quantity before reorder -->
    <restock-threshold>10</restock-threshold>
    
    <!-- Check inventory every 6 hours -->
    <check-interval>21600</check-interval>
    
    <!-- TODO: Implement predictive restocking based on sales trends -->
  </inventory>
  
  <!--
    Email Notifications
    Templates stored in /templates/email/
  -->
  <notifications>
    <!-- Send order confirmations immediately -->
    <order-confirmation enabled="true" delay="0" />
    
    <!-- Send shipping updates with 1-hour delay to batch processing -->
    <shipping-update enabled="true" delay="3600" />
    
    <!-- Disabled during A/B testing
    <promotional enabled="true" />
    -->
  </notifications>
  
</ecommerce-config>

Helpful Tools

Use these tools to work with your XML files:

XML Validator- Validate your XML syntax
XML Formatter- Format and beautify XML
XML Editor- Edit XML online

Learn More

XML Tools:

Related Articles