XML to JSON Conversion: Common Pitfalls and Solutions

XML

The XML-to-JSON Impedance Mismatch

XML and JSON model data differently. What seems like a mechanical conversion often produces surprising results. Understanding these differences prevents subtle bugs.

Attributes vs Elements

XML has two ways to attach data to a node — as an attribute or as a child element:

<user id="42" role="admin">
  <name>Alice</name>
</user>

Most converters map attributes to a @-prefixed key:

{
  "user": {
    "@id": "42",
    "@role": "admin",
    "name": "Alice"
  }
}

The API supports both the @ convention and a configurable attribute prefix.

Repeated Elements Become Arrays

<items>
  <item>a</item>
  <item>b</item>
</items>

becomes:

{ "items": { "item": ["a", "b"] } }

But a single child element may produce a string instead of a one-element array, depending on the library. The API normalises this with force_list options.

Namespaces

XML namespaces (xmlns:xsi) complicate keys. The API strips or preserves them based on the strip_namespaces flag (default: true).

API Usage

curl -X POST https://api.toolkitapi.io/v1/convert/xml-to-json \
  -H "X-API-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"xml": "<root><item>1</item><item>2</item></root>"}'

Round-Trip Fidelity

XML → JSON → XML rarely produces byte-identical output. If you need round-trip fidelity, store the canonical XML and use the JSON form only for querying. Use the Convert API's XML validation endpoint to check the source document is well-formed before converting.

Try it out

Browse Tools →

More from the Blog