XML to JSON and JSON to XML

Summary
Definition: XML and JSON are different data models that require explicit rules to convert between.
Why it matters: Incorrect assumptions can silently drop data or change meaning.
Pitfall: Attributes, order, and mixed content are easy to lose.
XML and JSON both represent structured data, but they use different data models.
Reliable conversion requires explicit mapping rules and acceptance of tradeoffs.
- XML element
- A tagged structure that contains data or other elements.
- Attribute
- Name-value metadata attached to an XML element.
- Mixed content
- Text and elements interleaved in XML.
- Convention
- A chosen rule not defined by a standard.
- Schema
- Rules that describe valid structure and data.
XML and JSON data models
XML is often document-centric, while JSON is data-centric.
Standards note
There is no universal, lossless mapping between arbitrary XML and JSON.
The W3C defines a specific XML representation of JSON for XPath, XQuery,
and XSLT. It does not define a general XML to JSON conversion.
Mapping elements and attributes
XML attributes have no direct equivalent in JSON. You must choose a convention,
such as storing attributes under a prefixed key.
Common mix-up: XML attributes do not automatically become JSON object keys.
A simple XML element with an attribute.
<user id="42">Ada</user>One possible JSON representation using conventions.
{
"user": {
"@id": "42",
"#text": "Ada"
}
}Different tools may use different keys or structures for attributes and text.
What does not convert cleanly
- XML mixed content.
- XML namespaces.
- Element ordering significance.
- Comments and processing instructions.
When not to convert
Avoid conversion when document order, mixed content, or namespaces carry meaning.
JSON cannot represent these features reliably.
Practical validation
- Define attribute and text conventions.
- Convert XML to JSON.
- Validate JSON output.
- Convert back only if required.
- Validate XML against schema if available.
Use with Encrypt Online
- Convert data using XML to JSON.
- Generate XML using JSON to XML.
- Validate formats before and after conversion.
FAQ
Is there a standard XML to JSON mapping? No. All XML to JSON mappings involve conventions and tradeoffs.
Do repeated XML elements become arrays? Often yes, but this is a convention, not a requirement.
Will comments convert? No. Comments and processing instructions are dropped.