using System;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Xml;
class Program
{
static void Main()
{
string xml = @"
<root>
<person>
<name>John</name>
<age>30</age>
</person>
<person>
<name>Jane</name>
<age>25</age>
</person>
</root>";
// 将 XML 字符串转换为 JSON 字符串
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string json = JsonConvert.SerializeXmlNode(doc);
Console.WriteLine("JSON: " + json);
// 如果需要格式化输出 JSON
dynamic jsonObj = JObject.Parse(json);
string formattedJson = jsonObj.ToString(Formatting.Indented);
Console.WriteLine("Formatted JSON: " + formattedJson);
}
}
Newtonsoft.Json
和 System.Xml
命名空间,以便处理 JSON 和 XML 数据。XmlDocument
类将 XML 字符串加载到内存中。JsonConvert.SerializeXmlNode
方法将 XML 转换为 JSON 格式。JObject.Parse
和 ToString(Formatting.Indented)
方法对生成的 JSON 进行格式化,使其更易读。确保你已经安装了 Newtonsoft.Json
包,可以通过 NuGet 包管理器安装:
Install-Package Newtonsoft.Json
上一篇:c# 对象转json
下一篇:c# namespace
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站