Yes. Using the JsonConvert class which contains helper methods for this precise purpose:

// To convert an XML node contained in string xml into a JSON string   
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);

// To convert JSON text contained in string json into an XML node
XmlDocument doc = JsonConvert.DeserializeXmlNode(json);

Documentation here: Converting between JSON and XML with Json.NET

Answer from David Brown on Stack Overflow
🌐
Newtonsoft
newtonsoft.com › json › help › html › ConvertXmlToJson.htm
Convert XML to JSON
string xml = @"<?xml version='1.0' standalone='no'?> <root> <person id='1'> <name>Alan</name> <url>http://www.google.com</url> </person> <person id='2'> <name>Louis</name> <url>http://www.yahoo.com</url> </person> </root>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); string json = JsonConvert.SerializeXmlNode(doc); Console.WriteLine(json); // { // "?xml": { // "@version": "1.0", // "@standalone": "no" // }, // "root": { // "person": [ // { // "@id": "1", // "name": "Alan", // "url": "http://www.google.com" // }, // { // "@id": "2", // "name": "Louis", // "url": "http://www.yahoo.com" // } // ] // } // }
Top answer
1 of 12
499

Yes. Using the JsonConvert class which contains helper methods for this precise purpose:

// To convert an XML node contained in string xml into a JSON string   
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);

// To convert JSON text contained in string json into an XML node
XmlDocument doc = JsonConvert.DeserializeXmlNode(json);

Documentation here: Converting between JSON and XML with Json.NET

2 of 12
60

Yes, you can do it (I do) but Be aware of some paradoxes when converting, and handle appropriately. You cannot automatically conform to all interface possibilities, and there is limited built-in support in controlling the conversion- many JSON structures and values cannot automatically be converted both ways. Keep in mind I am using the default settings with Newtonsoft JSON library and MS XML library, so your mileage may vary:

XML -> JSON

  1. All data becomes string data (for example you will always get "false" not false or "0" not 0) Obviously JavaScript treats these differently in certain cases.
  2. Children elements can become nested-object {} OR nested-array [ {} {} ...] depending if there is only one or more than one XML child-element. You would consume these two differently in JavaScript, etc. Different examples of XML conforming to the same schema can produce actually different JSON structures this way. You can add the attribute json:Array='true' to your element to workaround this in some (but not necessarily all) cases.
  3. Your XML must be fairly well-formed, I have noticed it doesn't need to perfectly conform to W3C standard, but 1. you must have a root element and 2. you cannot start element names with numbers are two of the enforced XML standards I have found when using Newtonsoft and MS libraries.
  4. In older versions, Blank elements do not convert to JSON. They are ignored. A blank element does not become "element":null

A new update changes how null can be handled (Thanks to Jon Story for pointing it out): https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_NullValueHandling.htm

JSON -> XML

  1. You need a top level object that will convert to a root XML element or the parser will fail.
  2. Your object names cannot start with a number, as they cannot be converted to elements (XML is technically even more strict than this) but I can 'get away' with breaking some of the other element naming rules.

Please feel free to mention any other issues you have noticed, I have developed my own custom routines for preparing and cleaning the strings as I convert back and forth. Your situation may or may not call for prep/cleanup. As StaxMan mentions, your situation may actually require that you convert between objects...this could entail appropriate interfaces and a bunch of case statements/etc to handle the caveats I mention above.

Discussions

Transforming XML to JSON in C++ - Software Engineering Stack Exchange
Working with XML in C++ seems a bit of a pain and I'm looking at a way to output JSON. I've stumbled on two different approaches: A) XSLT transformations: http://controlfreak.net/xml-to-json-in-... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
April 16, 2015
How to convert XML to JSON in C++? - Stack Overflow
I came across How to convert XML to JSON in ASP.NET C# (link) and one in javascript (at goessner.net/download/prj/jsonxml/). But have yet to find one in c++ that takes just a string as input (Or a More on stackoverflow.com
🌐 stackoverflow.com
JSON XML in C/C++ - Stack Overflow
I've been searching to no avail for a set of routines to do conversion between JSON and XML. I have found such routines in Javascript, Java, PHP, and Python, but not in C or C++. FWIW, my json lib... More on stackoverflow.com
🌐 stackoverflow.com
[C#] How to properly convert this XML into valid JSON?
Why not deserialize the XML into an object using System.XML then serialize that object to JSON using System.Text.Json? XML deserialization can get pretty tricky, so it's better to use a well established library. More on reddit.com
🌐 r/learnprogramming
5
1
July 8, 2021
🌐
GitHub
github.com › katie-snow › xml2json-c
GitHub - katie-snow/xml2json-c: A C library to pull in an XML file and have a json-c object available.
A C library to pull in an XML file and have a json-c object available. - katie-snow/xml2json-c
Author   katie-snow
🌐
GitHub
github.com › Cheedoong › xml2json
GitHub - Cheedoong/xml2json: A header-only C++ library converts XML to JSON · GitHub
xml2json is the first carefully written C++ library that converts XML document to JSON format.
Starred by 315 users
Forked by 103 users
Languages   C++ 84.3% | HTML 13.0% | C 2.5% | Makefile 0.2%
🌐
Medium
medium.com › @mbearz › strange-c-tricks-9-xml-to-json-using-jsonschema-6e4577c05852
Strange C# Tricks 9: XML to JSON using JsonSchema. | by Michael Berezin | Medium
February 22, 2024 - an object -we use a recursive call to the Parse method on the XML element and the nested schema to create a nested JSON object.
Find elsewhere
🌐
ReqBin
reqbin.com › xml-to-json
Online XML to JSON Converter
The XML to JSON converter lets you convert XML data strings to JSON objects. The XML converter is fully XML compliant and supports XML elements, attributes, texts, comments, CDATA, DOCTYPE, XML declarations, and XML processing instructions.
🌐
Code Beautify
codebeautify.org › xmltojson
XML to JSON Converter Online to convert XML to JSON String, URL and File
If you're looking for an easy way to convert XML to JSON, you've come to the right place. Our XML to JSON converter is free and easy to use, simply paste your XML code into the input and hit the "XML to JSON" button.
🌐
Reddit
reddit.com › r/learnprogramming › [c#] how to properly convert this xml into valid json?
r/learnprogramming on Reddit: [C#] How to properly convert this XML into valid JSON?
July 8, 2021 -

So I am using a third party API which is a SOAP server sending response strings that imitate a JSON structure, this is the return response I get from the server which is a list of addresses.

<return xsi:type="xsd:string">{&quot;res&quot;:&quot;
[]&quot;,&quot;res_addr&quot;:&quot;
[{\&quot;id\&quot;:\&quot;A_02774200\&quot;,\&quot;t\&quot;:\&quot;\\\&quot;\\u0100r
ai\\u0161u stacija\\\&quot; - 1, Drabe\\u0161u pag., 
C\\u0113su nov., LV-4101\&quot;},
{\&quot;id\&quot;:\&quot;A_02774201\&quot;,\&quot;t\&quot;:\&quot;\\\&quot;\\u0100ra
i\\u0161u stacija\\\&quot; - 2, Drabe\\u0161u pag., 
C\\u0113su nov., LV-4101\&quot;},
{\&quot;id\&quot;:\&quot;A_02774202\&quot;,\&quot;t\&quot;:\&quot;\\\&quot;\\u0100ra
i\\u0161u stacija\\\&quot; - 3, Drabe\\u0161u pag., 
C\\u0113su nov., LV-4101\&quot;}, ...

How do I properly convert the unicode letters and get rid of those backslashes &quot things to get a valid JSON?

Maybe this is a bad, dirty approach to the problem but what I did so far was use XDocument.Parse to get it to look like this

 <return xsi:type="xsd:string">{"res":"[]","res_addr":"
[{\"id\":\"A_02774200\",\"t\":\"\\\"\\u0100rai\\u0161u stacija\\\" - 1, Drabe\\u0161u pag., C\\u0113su nov., LV-4101\"},
{\"id\":\"A_02774201\",\"t\":\"\\\"\\u0100rai\\u0161u stacija\\\" - 2, Drabe\\u0161u pag., C\\u0113su nov., LV-4101\"},
{\"id\":\"A_02774202\",\"t\":\"\\\"\\u0100rai\\u0161u stacija\\\" - 3, Drabe\\u0161u pag., C\\u0113su nov., LV-4101\"},...

Then I used (string)doc.Descendants("return").Single() to get rid of the XML tags and I used the Regex.Unescape() command 2 times in a row

After the first one:

{"res":"[]","res_addr":"[{"id":"A_02774200","t":"\"\u0100rai\u0161u 
stacija\" - 1, Drabe\u0161u pag., C\u0113su nov., LV-4101"},
{"id":"A_02774201","t":"\"\u0100rai\u0161u stacija\" - 2, Drabe\u0161u pag., C\u0113su nov., LV-4101"},
{"id":"A_02774202","t":"\"\u0100rai\u0161u stacija\" - 3, Drabe\u0161u pag., C\u0113su nov., LV-4101"},
{"id":"A_02774203","t":"\"\u0100rai\u0161u stacija\" - 4, Drabe\u0161u pag., C\u0113su nov., LV-4101"},..

After the second one:

{"res":"[]","res_addr":"[{"id":"A_02774200","t":""Āraišu stacija" - 1, Drabešu pag., 
Cēsu nov., LV-4101"},{"id":"A_02774201","t":""Āraišu 
stacija" - 2, Drabešu pag., Cēsu nov., LV-4101"},
{"id":"A_02774202","t":""Āraišu stacija" - 3, Drabešu pag., Cēsu nov., LV-4101"},{"id":"A_02774203","t":""Āraišu stacija" - 4, Drabešu pag.,
 Cēsu nov., LV-4101"},{"id":"A_00420070","t":""Āraišu stacija" - 5,
 Drabešu pag., Cēsu nov., LV-4101"},

I also use .Replace("\"[","["); and .Replace("]\"", "]"); to remove the quotes next to [ and ] which also made the JSON invalid.

But I have run into a problem with some of the items where they have double quotes ("") inside of the t field containing double quotes which make it invalid JSON like this:

https://postimg.cc/w7zMLLNf

Is there maybe a string manipulation technique I could use to fix cases like this and to achieve a valid JSON or do I have to somehow convert the XML into JSON in a better way from the start not using the Regex.Unesacpe and string manipulations I did before?

Top answer
1 of 4
4
Why not deserialize the XML into an object using System.XML then serialize that object to JSON using System.Text.Json? XML deserialization can get pretty tricky, so it's better to use a well established library.
2 of 4
2
The built in JSON parser (in the System.Text.Json namespace) should be able to handle the unicode characters, so you don't have to worry about those. I haven't taken a super close look at the data, but it looks like all you need to do is fix the quotes and any double slashes? A couple of calls to string.Replace() should be able to fix that. EDIT: Something is up with your whatever you're doing, because simply by parsing the XML with XDocument.Parse(), everything is already handled. The " will be replaced with actual quotes, the double slashes should be replaced with single slashes, the escaped unicode characters should be replaced with the actual characters. I tried using your (incomplete) JSON to create my own, so I could use it in the example below. I'm not sure I reconstructed it properly though. Anyway, the code below works and produces valid JSON. var xml = "{"res":[{"res_addr":"ABC\u0113 123","id":"123879"}]}"; // XDocument.Parse can't handle XML namespaces by default... // I'm too lazy to figure out how properly handle that, so I cheated // by removing it from the XML before parsing. // If you can properly parse your XML with XDocument.Parse(), // then by all means continue with that and ignore the line below. xml = xml.Replace("xsi:type=\"xsd:string\"", null); var doc = XDocument.Parse(xml); var returnElement = doc.Descendants("return").Single(); var json = returnElement.Value; // This is now valid JSON.
🌐
JSON Formatter
jsonformatter.org › xml-to-json
Best XML to JSON Converter Online
XML to JSON is very unique tool for convert JOSN to XML and allows to download, save, share and print XML to JSON data..
🌐
InterSystems
community.intersystems.com › post › how-convert-xml-json
How to convert from XML to JSON? | InterSystems Developer Community
December 8, 2020 - The key issue I see is: Is there a Related XML schema available. If YES: - you can generate a package with the existing tools - import the file with %XML.Reader - do an %JSON... export The XML schema is necessary because straight XML is just TEXT with no datatypes while JSON has data types.
🌐
FreeFormatter
freeformatter.com › xml-to-json-converter.html
Free Online XML to JSON Converter - FreeFormatter.com
This free online tool lets you convert an XML file into a JSON file with your choice of indentation
🌐
Visual Studio Marketplace
marketplace.visualstudio.com › items
XML to JSON - Visual Studio Marketplace
Extension for Visual Studio Code - Convert XML from clipboard or current document/selection to JSON
🌐
GitHub
github.com › testillano › json2xml
GitHub - testillano/json2xml: C++ Converter from Json to XML (based in nlohmann::json sax consumer) · GitHub
C++ header-only converter from Json to XML, based in also header-only nlohmann json library.
Starred by 17 users
Forked by 3 users
Languages   C++ 48.9% | CMake 25.2% | Python 21.2% | Perl 2.4% | Dockerfile 2.3%
🌐
NVIDIA Developer Forums
forums.developer.nvidia.com › robotics & edge computing › jetson systems › jetson tx2
Working with XML and JSON files in C/C++ - Jetson TX2 - NVIDIA Developer Forums
August 7, 2023 - Hello, I need to configure my C/C++ software per XML or JSON. Know someone the proper possibility for that NVidia-SOM to parse the XML and JSON files for reading and writing ? We appreciate your help.
🌐
GitHub
gist.github.com › jj09 › c401d7066a2df1437987d4803fffcdb6
Convert XML to JSON in C# · GitHub
Excellent example, recently I published similar article on Converting JSON to XML and Vice-versa in C#. Using "Newtonsoft.Json" and without using it also, might be helpful for developers, so here is the link Converting JSON to XML OR XML to JSON using C#
🌐
Site24x7
site24x7.com › tools › xml-to-json.html
XML to JSON Converter: Site24x7 Tools
Free tool which converts your XML data to its equivalent JSON format.The XML elements are converted to JSON keys and element values are transformed to corresponding JSON values.
🌐
Aspose
products.aspose.com › aspose.cells › c++ › conversion › xml to json
C++ XML to JSON - XML to JSON Converter | products.aspose.com
September 29, 2025 - Aspose Excel. This comprehensive solution provides C++ developers with a fully integrated approach to convert XML to JSON format, enabling seamless saving of XML data into JSON format using the Aspose.Cells library, all through efficient and customizable C++ code.