dotnet json转xml格式
时间: 2023-09-20 12:06:22 浏览: 58
您可以使用XmlDocument类和Newtonsoft.Json.Linq.JObject类来实现将JSON转换为XML的过程。以下是示例代码:
```
using System.Xml;
using Newtonsoft.Json.Linq;
public static class JsonToXmlConverter
{
public static string Convert(string json)
{
JObject jsonObj = JObject.Parse(json);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadJson(jsonObj);
return xmlDoc.InnerXml;
}
private static void LoadJson(this XmlDocument xmlDoc, JToken token)
{
if (token == null)
return;
switch (token.Type)
{
case JTokenType.Object:
XmlElement objElement = xmlDoc.CreateElement(token.Path.Split('.').Last());
xmlDoc.DocumentElement?.AppendChild(objElement);
foreach (JProperty property in token.Children<JProperty>())
{
xmlDoc.LoadJson(property.Value);
}
break;
case JTokenType.Property:
xmlDoc.LoadJson(((JProperty)token).Value);
break;
case JTokenType.Array:
XmlElement arrayElement = xmlDoc.CreateElement(token.Path.Split('.').Last());
xmlDoc.DocumentElement?.AppendChild(arrayElement);
foreach (JToken value in token.Children())
{
xmlDoc.LoadJson(value);
}
break;
case JTokenType.Integer:
case JTokenType.Float:
case JTokenType.String:
case JTokenType.Boolean:
case JTokenType.Null:
XmlElement valueElement = xmlDoc.CreateElement(token.Path.Split('.').Last());
valueElement.InnerText = token.ToString();
xmlDoc.DocumentElement?.AppendChild(valueElement);
break;
case JTokenType.Date:
case JTokenType.Bytes:
case JTokenType.Guid:
case JTokenType.Uri:
default:
throw new InvalidOperationException("Unsupported JSON token type: " + token.Type);
}
}
}
```
您可以使用以下代码调用转换器:
```
string json = "{ \"name\": \"John Smith\", \"age\": 30, \"address\": { \"street\": \"123 Main St\", \"city\": \"Anytown\", \"state\": \"NY\" }, \"isMarried\": false, \"hobbies\": [ \"reading\", \"swimming\" ] }";
string xml = JsonToXmlConverter.Convert(json);
Console.WriteLine(xml);
```
这将输出以下XML字符串:
```
<name>John Smith</name>
<age>30</age>
<address>
<street>123 Main St</street>
<city>Anytown</city>
<state>NY</state>
</address>
<isMarried>false</isMarried>
<hobbies>
<hobbies>reading</hobbies>
<hobbies>swimming</hobbies>
</hobbies>
```