Convert XML to JSON in C: What Changes, What Gets Lost, and When to Avoid It
A practical review of converting XML to JSON in C: how the mapping works, what meaning it can lose, a libxml2 and cJSON sketch, and when to keep XML.
Converting XML to JSON in C means parsing an XML document, walking the result, and building an equivalent JSON value. The parsing and serializing are well-understood. The hard part is the mapping, because XML and JSON do not describe data the same way. This review covers what the conversion changes, where meaning can be lost, and when keeping the XML, or keeping the data as plain text, is the better choice.
Evidence note: no benchmarks, version-specific test results or measured outputs were supplied for this article. The guidance below rests on documented behavior of the XML and JSON formats and of widely used C libraries. The code sketch has not been compiled or run for this article, so treat it as a starting point and test it against your own documents.
Is this conversion suitable for your use?
Recommendation: convert XML to JSON in C when a downstream consumer requires JSON and the XML is data-oriented, such as records, configuration or message payloads with a stable, known shape. The main benefit is that JSON is simpler for most web services and scripting tools to consume. The decisive tradeoff is that no single XML-to-JSON mapping is lossless for every document. Attributes, mixed text, namespaces, comments, processing instructions and element order all need explicit decisions, and the generic choices can quietly change how the data is read.
Keep the XML, or extract plain text instead, in these situations:
- The XML is document-oriented, with prose and inline markup mixed together, as in DocBook, XHTML or similar formats.
- A consumer validates against an XML schema, or depends on signatures or canonical XML.
- Namespaces carry meaning that a downstream system must preserve.
- You only need the human-readable text. In that case, extracting text content is simpler and loses less than reshaping it into JSON.
- You cannot define a fixed schema for the JSON output. Without one, consumers have to guess whether a field will be a string, an object or an array.
What the conversion actually changes
Unlike pretty-printing or reformatting, this conversion changes the stored data model, not only how the data looks. Indenting or minifying the resulting JSON afterward is purely presentational and does not alter the data. Choosing how XML constructs map to JSON does alter it. The usual decision points are listed below.
| XML construct | Common JSON mapping | What can be lost or changed |
| Element | Object member keyed by element name | Nothing, if the name is unique among its siblings |
| Repeated sibling elements | Array under one key | Single and multiple occurrences produce different shapes |
| Attribute | Member with a prefix such as @ | Distinction from child elements relies on a naming convention |
| Text content | String, or a member such as #text | All values become strings; numbers and booleans are not inferred |
| Mixed content (text between child elements) | Separate text entries | Interleaving of text and elements is usually lost |
| Namespaces | Prefix dropped, or kept in the key | Two elements with the same local name can collide |
| Comments and processing instructions | Typically dropped | Gone entirely |
| Sibling order across different names | Object member order | JSON objects are defined as unordered, so consumers may reorder |
Two of these cause most real-world bugs. The first is array inconsistency. If an order has one item, a naive converter emits an object, but if it has two, it emits an array. Every consumer then has to handle both shapes. The second is type loss. XML text has no types, so "42" stays a string unless your code knows from a schema that the field is numeric and converts it deliberately.
Choosing libraries in C
C has no standard XML or JSON support, so a conversion almost always combines two libraries. On the XML side, libxml2 can parse a whole document into a tree you can walk, which is convenient for moderate-sized input. Expat is a streaming parser that reports elements through callbacks, which suits large inputs where loading a full tree is impractical, though it makes the mapping logic more involved. On the JSON side, cJSON, Jansson and json-c each let you build a value in memory and serialize it. The choice among them is mostly a matter of API preference, licensing review and what your project already depends on. No comparative measurements were available for this article, so performance claims between these libraries are not made here.
A minimal sketch with libxml2 and cJSON
The sketch below uses one explicit convention. Attributes become members prefixed with @, non-blank text becomes a #text member, and repeated names become arrays. Neither prefix can collide with an element name, because XML names cannot begin with @ or #. It drops namespace prefixes, comments and processing instructions, and it omits most allocation-failure checks for brevity.
#include <stdio.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <cjson/cJSON.h>
/* Add value under name; turn the member into an array on repeat. */
static void add_member(cJSON *obj, const char *name, cJSON *value)
{
cJSON *existing = cJSON_GetObjectItemCaseSensitive(obj, name);
if (!existing) {
cJSON_AddItemToObject(obj, name, value);
return;
}
if (!cJSON_IsArray(existing)) {
cJSON *arr = cJSON_CreateArray();
cJSON_DetachItemViaPointer(obj, existing);
cJSON_AddItemToArray(arr, existing);
cJSON_AddItemToObject(obj, name, arr);
existing = arr;
}
cJSON_AddItemToArray(existing, value);
}
static cJSON *element_to_json(xmlNode *node)
{
cJSON *obj = cJSON_CreateObject();
for (xmlAttr *attr = node->properties; attr; attr = attr->next) {
xmlChar *value = xmlNodeListGetString(node->doc, attr->children, 1);
char key[256];
snprintf(key, sizeof key, "@%s", (const char *)attr->name);
add_member(obj, key, cJSON_CreateString(value ? (const char *)value : ""));
xmlFree(value);
}
for (xmlNode *child = node->children; child; child = child->next) {
if (child->type == XML_ELEMENT_NODE) {
add_member(obj, (const char *)child->name, element_to_json(child));
} else if ((child->type == XML_TEXT_NODE ||
child->type == XML_CDATA_SECTION_NODE) &&
!xmlIsBlankNode(child)) {
add_member(obj, "#text", cJSON_CreateString((const char *)child->content));
}
}
return obj;
}
int main(int argc, char **argv)
{
if (argc != 2) {
fprintf(stderr, "usage: %s file.xml\n", argv[0]);
return 1;
}
/* XML_PARSE_NONET blocks network fetches; entity substitution stays off. */
xmlDoc *doc = xmlReadFile(argv[1], NULL, XML_PARSE_NONET);
if (!doc) {
fprintf(stderr, "failed to parse %s\n", argv[1]);
return 1;
}
xmlNode *root = xmlDocGetRootElement(doc);
if (!root) {
xmlFreeDoc(doc);
return 1;
}
cJSON *json = cJSON_CreateObject();
cJSON_AddItemToObject(json, (const char *)root->name, element_to_json(root));
char *out = cJSON_Print(json);
puts(out);
cJSON_free(out);
cJSON_Delete(json);
xmlFreeDoc(doc);
xmlCleanupParser();
return 0;
}
A typical build passes the flags reported by xml2-config or pkg-config for libxml2 and links cJSON. Header paths can differ between installations, so the cjson/cJSON.h include may need adjusting.
cc xml2json.c $(xml2-config --cflags --libs) -lcjson -o xml2json
Checking an example against the mapping
The following input and output are derived by tracing the code's logic, not from a recorded run. cJSON's own indentation will differ from what is shown here.
<order id="42">
<item sku="A1">Pen</item>
<item sku="B2">Ink</item>
<note>Ships & tracks</note>
</order>
{
"order": {
"@id": "42",
"item": [
{ "@sku": "A1", "#text": "Pen" },
{ "@sku": "B2", "#text": "Ink" }
],
"note": { "#text": "Ships & tracks" }
}
}
The output matches the described mechanism in several ways. The id stays the string "42" rather than becoming a number. The two item elements become an array, but a document with a single item would produce an object in that position instead. The whitespace-only text between elements is skipped. The & entity is decoded to a plain ampersand in the stored value. If the second item were removed, consumers that index item as an array would break, which is why a fixed schema, or a rule that always emits arrays for known repeating elements, is worth adding before production use.
Will the result stay readable and usable after sharing?
Several practical limits affect whether the JSON stays usable once it leaves your program:
- Encoding: libxml2 stores parsed text internally as UTF-8 regardless of the declared input encoding, and JSON exchanged between systems is expected to be UTF-8. A correctly declared input in another encoding should therefore come out as UTF-8. Input with a wrong or missing encoding declaration can still produce garbled text, and the converter cannot detect that on its own.
- Escaping: the JSON library handles quoting of characters such as quotation marks, backslashes and control characters. Hand-building JSON strings with printf is a common source of invalid output and should be avoided.
- Order: arrays keep their element order, but JSON objects are formally unordered. If the relative order of differently named elements matters, as it does in document-style XML, an object-based mapping does not reliably preserve it.
- Round-tripping: converting the JSON back to XML will not reproduce the original document. Comments, namespace prefixes, mixed-content interleaving and the distinction between an attribute and a child element under some conventions are not recoverable.
- Copying and editing: pretty-printed output is easier to review and diff, while minified output is smaller. Both carry identical data, so pick whichever suits the destination.
Accessibility, screen-reader behavior and search indexing are not meaningfully affected by this conversion, since its output is machine data rather than displayed text. If the content is ultimately shown to people, render it from the data rather than displaying the raw JSON.
Security when the input is untrusted
XML parsers can be pushed into fetching external resources or expanding entities in harmful ways. With libxml2, leave entity substitution off for untrusted input by not passing XML_PARSE_NOENT, keep network access disabled with XML_PARSE_NONET, and avoid options that load external DTDs unless you need them. Also set limits on input size and nesting depth. The recursive walk in the sketch has no depth limit, so very deep documents could exhaust the stack.
Gaps in this review
No benchmark data, memory measurements, library version comparisons or tested destination systems were available. Claims about speed, footprint or compatibility with a specific consumer would need your own scoped tests. The code sketch should be compiled, run against representative documents and checked under a memory-error detector before you rely on it.