Skip to content
uencoder
TUTORIAL

How to Convert JSON to XML

Convert JSON data to XML format, handling arrays, nested objects, and attributes.

Problem

You need to send data to a system that expects XML, but your source data is in JSON format.

Prerequisites

  • Understanding of JSON
  • Understanding of XML structure

Steps

  1. 1. Define the conversion rules

    JSON objects become XML elements, keys become tag names, and values become element content. Arrays need special handling: each element becomes a repeated child tag. Decide on a root element name and how to represent arrays and null values.

    Input
    {"users":[{"name":"Alice"}]}
    Output
    rules defined
  2. 2. Perform the conversion

    Convert the JSON to XML following your rules. Nested objects become nested elements. Array items use the parent key as the tag name. Strings become text content; numbers and booleans become text content (XML has no native types).

    Input
    {"users":[{"name":"Alice"}]}
    Output
    <users><name>Alice</name></users>
  3. 3. Validate the XML output

    Parse the resulting XML to ensure it is well-formed. Check that all tags are closed, special characters are escaped (& < > are escaped as &amp; &lt; &gt;), and the encoding declaration is correct if needed.

    Input
    <users><name>Alice</name></users>
    Output
    well-formed XML ✓

Expected result

A well-formed XML document that represents the same data as the original JSON.

Common errors

XML tags start with a number or contain spaces
XML tag names must start with a letter or underscore and cannot contain spaces. Sanitize JSON keys before converting.
Special characters not escaped
Escape &, <, >, ", and ' as XML entities. The converter should handle this automatically.

Troubleshooting

  • If the XML parser rejects the output, check for unescaped special characters and unclosed tags.
  • JSON null has no direct XML equivalent. Decide on a convention (empty element, xsi:nil attribute, or omission).

Security limits

  • XML can be vulnerable to XXE (XML External Entity) attacks if parsed with an unsafe parser. Use a parser that disables DTD and external entities.

Related tools

Related tasks

Ready to run it?

References