Self-Closing XML Tags and Empty Elements
Learn how self-closing XML tags and empty elements are handled in JSON conversion. Covers null mapping, empty string vs null, and preserving the distinction.
Detailed Explanation
Self-closing tags (empty elements) in XML represent elements with no content. They are shorthand for an open-close tag pair with nothing between them, and their JSON mapping requires careful consideration.
XML with self-closing tags:
<user>
<name>Alice</name>
<email>alice@example.com</email>
<phone/>
<avatar></avatar>
<bio/>
<settings enabled="true"/>
</user>
Note: <phone/> and <phone></phone> are semantically identical in XML.
JSON conversion options:
Option 1: Map to null
{
"user": {
"name": "Alice",
"email": "alice@example.com",
"phone": null,
"avatar": null,
"bio": null,
"settings": { "@enabled": "true" }
}
}
Option 2: Map to empty string
{
"user": {
"name": "Alice",
"email": "alice@example.com",
"phone": "",
"avatar": "",
"bio": "",
"settings": { "@enabled": "true" }
}
}
Option 3: Map to empty object
{
"user": {
"phone": {},
"settings": { "@enabled": "true" }
}
}
Which option to choose:
| Scenario | Best mapping | Reason |
|---|---|---|
| Field is optional/absent | null |
Semantically represents "no value" |
| Field expects text but is empty | "" |
Preserves the field with empty content |
| Element may have attributes | {} |
Allows attribute keys alongside content |
| Element with attributes only | { "@attr": "val" } |
Preserves attribute data |
Self-closing tags with attributes are a special case. <settings enabled="true"/> has no text content but does have an attribute. In JSON:
{ "settings": { "@enabled": "true" } }
When converting JSON to XML:
| JSON value | XML output |
|---|---|
null |
<field/> or <field xsi:nil="true"/> |
"" |
<field></field> or <field/> |
{} |
<field/> |
The distinction between null, empty string, and empty object in JSON all collapse to the same self-closing tag in XML. This is one of the areas where round-trip conversion can lose information.
Best practice: Use null for empty elements when converting XML to JSON, unless the consuming code specifically needs empty strings. Document the convention so consumers know how to interpret null values.
Use Case
Parsing a user profile XML document where optional fields like phone number and avatar URL use self-closing tags to indicate no value, and mapping them to null in the JSON representation for a REST API response.