SoFunction
Updated on 2025-03-07

Use JSON and XML to convert each other in C#

Official address
/pages/

XML TO JSON

string xml = @"<?xml version=""1.0"" standalone=""no""?>
<root>
 <person id=""1"">
 <name>Alan</name>
 <url></url>
 </person>
 <person id=""2"">
 <name>Louis</name>
 <url></url>
 </person>
</root>";
 
XmlDocument doc = new XmlDocument();
(xml);
 
string jsonText = (doc);
//{
// "?xml": {
//  "@version": "1.0",
//  "@standalone": "no"
// },
// "root": {
//  "person": [
//   {
//    "@id": "1",
//    "name": "Alan",
//    "url": ""
//   },
//   {
//    "@id": "2",
//    "name": "Louis",
//    "url": ""
//   }
//  ]
// }
//}

JSON TO XML

string json = @"{
 ""?xml"": {
  ""@version"": ""1.0"",
  ""@standalone"": ""no""
 },
 ""root"": {
  ""person"": [
   {
    ""@id"": ""1"",
    ""name"": ""Alan"",
    ""url"": """"
   },
   {
    ""@id"": ""2"",
    ""name"": ""Louis"",
    ""url"": """"
   }
  ]
 }
}";
 
XmlDocument doc = (XmlDocument)(json);
// <?xml version="1.0" standalone="no"?>
// <root>
//  <person >
//  <name>Alan</name>
//  <url></url>
//  </person>
//  <person >
//  <name>Louis</name>
//  <url></url>
//  </person>
// </root>

DEMO:JSON TO XML

string json_str = "{\"a\":\"a\",\"b\":\"b\"}";
//Json's string needs to be written in this format, otherwise an error will be reportedstring json = @"{
 ""?xml"": {
  ""@version"": ""1.0"",
  ""@standalone"": ""no""
 },
 ""root"":" + json_str + "}";
 
if (!(json))
{
  XmlDocument doc = (json);
   
}