Developer Documentation
C#
Updated September 19, 2026

Convert XML to JSON in C#

Parse XML and convert it to JSON using an explicit mapping convention in C#.

XML can represent attributes, mixed text, namespaces, repeated elements, and ordering in ways JSON cannot represent directly. Pick a library and a stable mapping convention, then test it with real documents.

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;45var doc = new XmlDocument();6doc.LoadXml(xml);7string json = JsonConvert.SerializeXmlNode(doc, Formatting.Indented);8Console.WriteLine(json);

Common Operations#

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

Control the root#

C#
1XmlElement root = doc.DocumentElement2    ?? throw new InvalidDataException("XML document has no root element");34string json = JsonConvert.SerializeXmlNode(root, Formatting.None, omitRootObject: false);

Important Notes#

Disable or avoid dangerous external entity behavior when parsing untrusted XML and test the library mapping for attributes, arrays, and text nodes.

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 XML → JSON in other languages: