These days, when exchanging messages between different apps or services, complex structured data is mostly converted to JSON. Of course, there are still many places that use XML. Therefore, there are cases where the data received in XML needs to be serialized to JSON and stored or sent to another node.
In such cases, you can easily serialize it with just a method call using Json.NET.
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"
// }
// ]
// }
// }
Original text: https://www.newtonsoft.com/json/help/html/ConvertXmlToJson.htm
ยฉ 2025 juniyunapapa@gmail.com.