C# 将Json字符串转换为Xml

C# 将Json字符串转换为Xml,c#,json,xml,C#,Json,Xml,我是一个新的程序员,我真的被卡住了(可能是因为太新,知识太少),我需要转换一个json字符串(如下所示): 转换为XML,如下所示: [ { "Start": "date", "Finish": "date", "Subject": "", "Comments": "", "Site": "address", "Location": null, "Status": false, "Arrived": true, "Nos

我是一个新的程序员,我真的被卡住了(可能是因为太新,知识太少),我需要转换一个json字符串(如下所示):

转换为XML,如下所示:

[
  {
    "Start": "date",
    "Finish": "date",
    "Subject": "",
    "Comments": "",
    "Site": "address",
    "Location": null,
    "Status": false,
    "Arrived": true,
    "Noshow": false,
    "Services": "Initial Consultation",
    "Attendees": [
      {
        "AccountId": 1111,
        "AccountType": "MP",
        "Name": "MMS (FP), Support "
      },
      {
        "AccountId": 2220915,
        "AccountType": "PA",
        "Name": "Test, Patient "
      }
    ]
  },
]
<?xml version="1.0" encoding="UTF-8"?>
   <root>
   <element>
      <Arrived>true</Arrived>
      <Attendees>
         <element>
            <AccountId>1111</AccountId>
            <AccountType>MP</AccountType>
            <Name>MMS(FP), Support</Name>
         </element>
         <element>
            <AccountId>2220915</AccountId>
            <AccountType>PA</AccountType>
            <Name>Test, Patient</Name>
         </element>
      </Attendees>
      <Comments />
      <Finish>date</Finish>
      <Location null="true" />
      <Noshow>false</Noshow>
      <Services>Initial Consultation</Services>
      <Site>address</Site>
      <Start>date</Start>
      <Status>false</Status>
      <Subject />
   </element>
</root>`

真的
1111
议员
彩信(FP),支持
2220915
帕
检查,病人
日期
假的
初步咨询
地址
日期
假的
`
并尝试在谷歌上搜索各种答案,但都无济于事。我尝试了大量的JsonConvert.DecryptXmlNode(文件名)的排列但这些都是错误。 我遇到的错误包括“根级别的数据无效”和“只能转换以有效对象开头的json”

为了澄清,我收到了数百个Json文件(不知道其中包含什么),需要一种“一网打尽”的场景

提前谢谢。

您需要:

// Calling your JSON deserialization to create an array of dictionarys
var items = json.FromJson<Dictionary<string, object>[]>();
var xml = new XElement("root", 
                            items
                                .Select(it => new XElement("element", 
                                                    it.Select(el => ToXml(el.Key, el.Value)))));    

// method to create xml from a key value pair
XElement ToXml(string key, object item)
{
    if(item is JArray data){
        var items = data.ToString()
                        .FromJson<Dictionary<string, object>[]>();
        return new XElement(key, items.Select(dt => items
                                                    .Select(it => new XElement("element",
                                                            it.Select(el => ToXml(el.Key, el.Value))))));
    }
    return new XElement(key, item);
}

// In a separate class
public static class Extensions
{
    // This uses NewtonSoft.Json for deserialization
    public static T FromJson<T>(this string json)
    {
        var serializer = new JsonSerializer();
        using (var sr = new StringReader(json))
        using (var jr = new JsonTextReader(sr))
        {
            var result = serializer.Deserialize<T>(jr);
            return result;
        }
    }
}
//调用JSON反序列化来创建字典数组
var items=json.FromJson();
var xml=new-XElement(“根”,
项目
.Select(it=>newxelement(“元素”),
it.Select(el=>ToXml(el.Key,el.Value‘‘‘‘));
//方法从键值对创建xml
XElement ToXml(字符串键,对象项)
{
if(项目为JArray数据){
var items=data.ToString()
.FromJson();
返回新的XElement(键,items.Select(dt=>items
.Select(it=>newxelement(“元素”),
it.Select(el=>ToXml(el.Key,el.Value‘‘‘‘‘‘));
}
返回新的元素(键、项);
}
//分班
公共静态类扩展
{
//这使用NewtonSoft.Json进行反序列化
公共静态T FromJson(此字符串为json)
{
var serializer=new JsonSerializer();
使用(var sr=newstringreader(json))
使用(var jr=新的JsonTextReader(sr))
{
var result=serializer.Deserialize(jr);
返回结果;
}
}
}
您需要:

// Calling your JSON deserialization to create an array of dictionarys
var items = json.FromJson<Dictionary<string, object>[]>();
var xml = new XElement("root", 
                            items
                                .Select(it => new XElement("element", 
                                                    it.Select(el => ToXml(el.Key, el.Value)))));    

// method to create xml from a key value pair
XElement ToXml(string key, object item)
{
    if(item is JArray data){
        var items = data.ToString()
                        .FromJson<Dictionary<string, object>[]>();
        return new XElement(key, items.Select(dt => items
                                                    .Select(it => new XElement("element",
                                                            it.Select(el => ToXml(el.Key, el.Value))))));
    }
    return new XElement(key, item);
}

// In a separate class
public static class Extensions
{
    // This uses NewtonSoft.Json for deserialization
    public static T FromJson<T>(this string json)
    {
        var serializer = new JsonSerializer();
        using (var sr = new StringReader(json))
        using (var jr = new JsonTextReader(sr))
        {
            var result = serializer.Deserialize<T>(jr);
            return result;
        }
    }
}
//调用JSON反序列化来创建字典数组
var items=json.FromJson();
var xml=new-XElement(“根”,
项目
.Select(it=>newxelement(“元素”),
it.Select(el=>ToXml(el.Key,el.Value‘‘‘‘));
//方法从键值对创建xml
XElement ToXml(字符串键,对象项)
{
if(项目为JArray数据){
var items=data.ToString()
.FromJson();
返回新的XElement(键,items.Select(dt=>items
.Select(it=>newxelement(“元素”),
it.Select(el=>ToXml(el.Key,el.Value‘‘‘‘‘‘));
}
返回新的元素(键、项);
}
//分班
公共静态类扩展
{
//这使用NewtonSoft.Json进行反序列化
公共静态T FromJson(此字符串为json)
{
var serializer=new JsonSerializer();
使用(var sr=newstringreader(json))
使用(var jr=新的JsonTextReader(sr))
{
var result=serializer.Deserialize(jr);
返回结果;
}
}
}

在开始之前,我建议使用验证JSON。
外部方括号是不必要的,理想情况下应删除结尾处的逗号

现在,由于您提到您正在使用C#和Newtonsoft Json.NET,您可以在控制台程序的program.cs文件中尝试:

using System;
using System.Xml.Linq; //For the XDocument class
using Newtonsoft.Json; //For JsonConvert class
using System.IO; //For File class

class JsonToXMLProgram
{
    static void Main(string[] args)
    {
        string myJSONString = @File.ReadAllText(@"H:\MyJsonFile.json"); //Replace with your json files' locations.

        //This converts the JSON string to xml
        XDocument myXMLDocument = JsonToXML(myJSONString);

        //you could then check your xml by outputting it to the console...
        Console.WriteLine(myXMLDocument.ToString());
        //..or by saving the file to disk
        string myXMLFilePath = @"H:\MyXmlDocument.xml"; //Replace with the path to your generated xml files.
        myXMLDocument.Save(myXMLFilePath);
    }


    public static XDocument JsonToXML(string jsonString)
    {
        XDocument xmlDoc;
        try
        {
            xmlDoc = JsonConvert.DeserializeXNode(jsonString, "Root", true);
            return xmlDoc;
        }
        catch (JsonException e)
        {
            Console.WriteLine("There appears to be an error in the json file. Please validate the json to ensure that it is free from errors.");
            Console.WriteLine("Details: " + e.Message);
            return new XDocument();
        }
    }
}

在开始之前,我建议使用验证JSON。
外部方括号是不必要的,理想情况下应删除结尾处的逗号

现在,由于您提到您正在使用C#和Newtonsoft Json.NET,您可以在控制台程序的program.cs文件中尝试:

using System;
using System.Xml.Linq; //For the XDocument class
using Newtonsoft.Json; //For JsonConvert class
using System.IO; //For File class

class JsonToXMLProgram
{
    static void Main(string[] args)
    {
        string myJSONString = @File.ReadAllText(@"H:\MyJsonFile.json"); //Replace with your json files' locations.

        //This converts the JSON string to xml
        XDocument myXMLDocument = JsonToXML(myJSONString);

        //you could then check your xml by outputting it to the console...
        Console.WriteLine(myXMLDocument.ToString());
        //..or by saving the file to disk
        string myXMLFilePath = @"H:\MyXmlDocument.xml"; //Replace with the path to your generated xml files.
        myXMLDocument.Save(myXMLFilePath);
    }


    public static XDocument JsonToXML(string jsonString)
    {
        XDocument xmlDoc;
        try
        {
            xmlDoc = JsonConvert.DeserializeXNode(jsonString, "Root", true);
            return xmlDoc;
        }
        catch (JsonException e)
        {
            Console.WriteLine("There appears to be an error in the json file. Please validate the json to ensure that it is free from errors.");
            Console.WriteLine("Details: " + e.Message);
            return new XDocument();
        }
    }
}

如果xml未加密,则无法解密。这就是为什么会出现错误。有很多库可以将JSON转换成XML,但它们很少能生成您想要的XML。通常有必要在转换之后进行自定义转换(例如在XSLT中),将XML映射到所需的格式。对于一个JSON文件来说,这已经足够简单了,但是对于数百个JSON文件来说,当您不知道其中包含什么时,这样做并不容易;您需要更清楚地了解您正在生成的XML将如何使用,以及消费者的期望是什么。这是一个数组。这就是为什么xml使用
元素在根附近和
与会者中保存值的原因。如果xml未加密,则无法解密。这就是为什么会出现错误。有很多库可以将JSON转换成XML,但它们很少能生成您想要的XML。通常有必要在转换之后进行自定义转换(例如在XSLT中),将XML映射到所需的格式。对于一个JSON文件来说,这已经足够简单了,但是对于数百个JSON文件来说,当您不知道其中包含什么时,这样做并不容易;您需要更清楚地了解您正在生成的XML将如何使用,以及消费者的期望是什么。这是一个数组。这就是为什么xml使用
元素来保存根附近和
与会者中的值的原因。外部方括号毫无意义,但完全合法。倒数第二行的逗号是非法的,但被许多JSON解析器接受。@MichaelKay更新了答案以反映这一点,谢谢。外方括号是没有意义的,但根据