Developer Documentation
C#
Updated September 19, 2026

Convert JSON to XML in C#

Convert JSON objects to XML while making the mapping rules explicit in C#.

JSON and XML have different data models, so there is no single universal conversion. Libraries make choices about roots, arrays, attributes, text nodes, nulls, and invalid XML element names; document those choices in APIs.

Quick Start#

The following example uses the standard C# API or a widely used package for this task.

Using Newtonsoft.Json#

C#
1// dotnet add package Newtonsoft.Json2using Newtonsoft.Json;3using System.Xml;45XmlDocument? doc = JsonConvert.DeserializeXmlNode(inputJson, "root");6string xml = doc?.OuterXml ?? "<root />";7Console.WriteLine(xml);

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

Indented XML#

C#
1using var stringWriter = new StringWriter();2using var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { Indent = true });3doc!.Save(xmlWriter);4xmlWriter.Flush();5string prettyXml = stringWriter.ToString();

Important Notes#

The JSON/XML mapping used by Newtonsoft.Json is a convention. Verify arrays, attributes, and text nodes against the documents your application needs to exchange.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#

Implement JSON → XML in other languages: