Recipe 12.5 · C#
Converting Between XML and JSON
Problem
A legacy service returns XML and the new front end wants JSON. Or the reverse: a modern API posts JSON that must be forwarded to a mainframe gateway that only accepts XML. You need a predictable conversion, and the obvious library call has a habit of changing the shape of its output depending on the data.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
// Not to copy: shape depends on the data, pulls in Newtonsoft.Json
var doc = new XmlDocument();
doc.LoadXml(xml);
string json = JsonConvert.SerializeXmlNode(doc);
SerializeXmlNode is convenient, and it hides one real flaw. An order with two <Line> elements
becomes "Line": [ ... ], while an order with one becomes "Line": { ... }. Every consumer has to
handle both shapes, and the first order with a single line breaks the front end in production.
The improved recipe
Write the conversion yourself over XElement and JsonNode. It is short, uses only the base class
library, and lets the caller name the elements that are always arrays.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Xml.Linq;
namespace ImproveCode.Serialization;
/// <summary>
/// Attributes become "@name", mixed text becomes "#text".
/// Element names in arrayNames are always written as JSON arrays.
/// </summary>
public static class XmlJsonConverter
{
public static JsonObject ToJson(
XElement root, IReadOnlySet<string>? arrayNames = null)
{
arrayNames ??= new HashSet<string>();
return new JsonObject
{
[root.Name.LocalName] = ConvertElement(root, arrayNames),
};
}
public static XElement ToXml(JsonObject json)
{
if (json.Count != 1)
{
throw new ArgumentException(
"JSON must have exactly one root property.",
nameof(json));
}
var (name, node) = json.First();
return BuildElement(name, node);
}
private static JsonNode? ConvertElement(
XElement element, IReadOnlySet<string> arrayNames)
{
var attributes = element.Attributes()
.Where(a => !a.IsNamespaceDeclaration)
.ToList();
if (attributes.Count == 0 && !element.HasElements)
{
return element.IsEmpty
? null
: JsonValue.Create(element.Value);
}
var result = new JsonObject();
foreach (XAttribute attribute in attributes)
{
result["@" + attribute.Name.LocalName] = attribute.Value;
}
foreach (var group in element.Elements()
.GroupBy(e => e.Name.LocalName))
{
var items = group
.Select(e => ConvertElement(e, arrayNames))
.ToArray();
result[group.Key] =
items.Length == 1 && !arrayNames.Contains(group.Key)
? items[0]
: new JsonArray(items);
}
if (!element.HasElements && element.Value.Length > 0)
{
result["#text"] = element.Value;
}
return result;
}
private static XElement BuildElement(string name, JsonNode? node)
{
var element = new XElement(name);
switch (node)
{
case null:
break;
case JsonObject obj:
foreach (var (key, child) in obj)
{
AddMember(element, key, child);
}
break;
default:
element.Value = ScalarText(node);
break;
}
return element;
}
private static void AddMember(
XElement parent, string key, JsonNode? child)
{
if (key.StartsWith('@'))
{
parent.SetAttributeValue(key[1..], ScalarText(child));
}
else if (key == "#text")
{
parent.Add(new XText(ScalarText(child)));
}
else if (child is JsonArray array)
{
foreach (JsonNode? item in array)
{
parent.Add(BuildElement(key, item));
}
}
else
{
parent.Add(BuildElement(key, child));
}
}
private static string ScalarText(JsonNode? node) =>
node switch
{
null => "",
JsonValue v when v.GetValueKind() == JsonValueKind.String
=> v.GetValue<string>(),
_ => node.ToJsonString(),
};
}
Usage, with Line declared as an array element:
var arrays = new HashSet<string> { "Line" };
JsonObject json = XmlJsonConverter.ToJson(
XElement.Parse(orderXml), arrays);
string text = json.ToJsonString(JsonDefaults.Indented);
XElement back = XmlJsonConverter.ToXml(json);
An order with a single line now always produces this shape:
{
"Order": {
"@id": "1001",
"Customer": "Example Supply Co.",
"Line": [
{ "@sku": "A-100", "#text": "19.98" }
]
}
}
How it works
The conversion follows the convention most XML-to-JSON tools use, so the output looks familiar.
An element with no attributes and no children becomes a plain string. Anything else becomes an
object: attributes get an @ prefix, child elements are grouped by name, and the text of an
element that also has attributes goes under #text.
Grouping by name is what decides between a single value and an array. The arrayNames set
overrides that decision for the names you list, which removes the data-dependent shape. In
practice you know which elements repeat, usually from the partner's schema, so the list is short
and stable.
The reverse direction walks the JsonObject. Properties starting with @ become attributes,
#text becomes a text node, arrays become repeated sibling elements, and nested objects recurse.
ScalarText writes strings without quotes and other values, such as numbers and booleans, in
their JSON form.
I tested the round trip on a generated order: XML to JSON to XML produced an element that compared
equal to the original with XNode.DeepEquals.
Variations and pitfalls
- XML has no types. Every value comes out of
ToJsonas a string, including19.98. If the consumer needs numbers, deserialize the JSON into a typed DTO withJsonNumberHandling.AllowReadingFromString, whichJsonSerializerDefaults.Webalready enables. - Namespaces are dropped. The converter keeps local names only. That is usually what a JSON
consumer wants. If you must round-trip namespaces, add them back in
ToXmlwith anXNamespace. - Mixed content such as
<p>Hello <b>world</b></p>does not map cleanly to JSON with any convention. Treat it as an opaque string withelement.ToString()instead. - Often the better answer is two typed models. If you control both sides, deserialize the XML
with
XmlSerializer, map to a DTO, and serialize that withSystem.Text.Json. The generic converter earns its place for pass-through gateways and for documents with many shapes.