July 22, 2026
XML to JSON: Taming Attributes, Namespaces, and Mixed Content
Converting XML to JSON maps each child element to a JSON key directly when the XML is simple and flat. The complications come from XML attributes, which need a naming convention like "@id" since JSON has no attribute concept, and repeated elements, which should consistently become arrays even when there's only one instance — otherwise the JSON's shape can silently change between documents.

Elements become keys, straightforwardly
A simple XML structure like <user><name>Sam</name><age>29</age></user> converts cleanly: each child element becomes a JSON key, its text content becomes the value. This case — plain nested elements, no attributes, no repetition — is where XML-to-JSON conversion is close to lossless.
Attributes need a convention
XML attributes (<user id="42">) don't map onto JSON's key-value model automatically, since JSON has no separate "attribute" concept. Most converters adopt a prefix convention — commonly turning id="42" into a key like "@id": "42" or "_id": "42" — to distinguish attributes from child elements in the output. It's worth knowing which convention a given converter uses before writing code against its output.
Repeated elements become arrays — but single ones might not
When an XML element repeats — multiple <item> tags inside a parent — a converter turns them into a JSON array. The subtle bug: if a document happens to have exactly one <item> in one instance and multiple in another, some converters will output a single object in the first case and an array in the second, silently changing your JSON's shape based on data that has nothing to do with your actual schema. Good converters normalize known-repeatable elements to always be arrays, even with a single item.
Mixed content doesn't translate at all
XML documents can mix text and child elements freely — <p>Hello <b>world</b>!</p> has text before, inside, and after a nested element. JSON has no equivalent structure for that; converting this kind of document-style XML to JSON necessarily loses some of that interleaving. This is rarely an issue for data-oriented XML (config files, API responses) but matters for document-style XML like DocBook or XHTML content.
- Good fit: data-oriented XML — config files, RSS/Atom feeds, structured API responses
- Poor fit: document-style XML with mixed text and markup, where structure carries meaning beyond simple nesting
Want to try this yourself?
Open XML to JSON →