XML Comments and JSON Conversion
Understand how XML comments are handled during JSON conversion. Learn about comment syntax, why comments are typically discarded, and strategies for preserving comment content.
Detailed Explanation
XML comments are annotations within the document that are not part of the data content. Like YAML comments, they are typically discarded during JSON conversion since JSON has no comment syntax.
XML with comments:
<config>
<!-- Database settings -->
<database>
<host>localhost</host> <!-- Primary DB host -->
<port>5432</port> <!-- Default PostgreSQL port -->
<name>myapp_prod</name>
</database>
<!-- Cache configuration -->
<!-- TODO: Add Redis cluster support -->
<cache>
<driver>redis</driver>
<ttl>3600</ttl> <!-- TTL in seconds -->
</cache>
</config>
Converted to JSON (comments discarded):
{
"config": {
"database": {
"host": "localhost",
"port": "5432",
"name": "myapp_prod"
},
"cache": {
"driver": "redis",
"ttl": "3600"
}
}
}
Why comments are lost:
- JSON has no comment syntax. Unlike JSONC (used by VS Code), standard JSON per RFC 8259 does not support comments.
- XML DOM parsers typically ignore comments. When an XML document is parsed into a DOM tree, comment nodes exist in the tree but are skipped during data extraction.
- Comments are metadata, not data. They describe intent and context for human readers, not machine-processable information.
Preserving comments (if needed):
Strategy 1: Special keys
{
"database": {
"_comment": "Database settings",
"host": "localhost",
"port": "5432"
}
}
Strategy 2: Comment array
{
"_comments": [
"Database settings",
"TODO: Add Redis cluster support"
],
"database": { "host": "localhost" }
}
XML comment rules:
- Comments start with
<!--and end with--> - The string
--(double hyphen) is not allowed inside a comment body - Comments cannot appear inside element tags:
<element <!-- bad --> attr="val">is invalid - Comments can appear before the root element, after the root element, and anywhere between child elements
When converting JSON to XML, you cannot generate comments from standard JSON data. If the JSON contains _comment keys, a smart converter could translate those into XML comments, but this is not a standard feature.
Use Case
Converting a heavily commented XML configuration file to JSON for programmatic manipulation, then converting back to XML while documenting that inline comments will not survive the round trip.