c# - 将多个 json 文件转换为 xml 文件
问题描述
我是一个相对较新的程序员,因此知识有限;但是,我被要求创建一个程序来将大量 json 文件转换为 xml 文件。它们有很多,而且它们在内容方面都不同(我不知道它们到底是什么)。
我试过下面的代码
static void ProcessFiles(string path)
{
string[] files;
string[] directories;
XmlDocument xml = new XmlDocument();
files = Directory.GetFiles(path);
foreach (string file in files)
{
using (StreamReader r = new StreamReader(file))
{
string j = r.ReadToEnd();
string json = JsonConvert.DeserializeObject(j).ToString();
xml = JsonConvert.DeserializeXmlNode(json);
Console.Write(xml);
}
}
directories = Directory.GetDirectories(path);
foreach(string directory in directories)
{
ProcessFiles(directory);
}
}
我设法把它作为我的字符串'json'然后得到一个错误。
[
{
"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 "
}
]
},
]
我一直在网上寻找解决方案,但到目前为止还没有运气。有人可以帮忙吗?
解决方案
你接近你的目标,
所以现在你正在这样做,
StreamReader
从with 中读取字符串 jsonReadToEnd
- 然后反序列化成
dynamic
变量。 - 然后加载到xml中。
但是在第 3 点,您试图将json
字符串传递给LoadXml
方法,其中LoadXml
需要 xml 字符串作为输入。
到目前为止,newtonsoft 有一种方法可以直接将您的 json 转换为 xml
XmlDocument xdoc = JsonConvert.DeserializeXmlNode(json);
所以现在你的代码看起来像,
//Your code as it is
using (StreamReader r = new StreamReader(file))
{
string json = r.ReadToEnd();
xdoc = JsonConvert.DeserializeXmlNode(json);
xdoc.Save(file + ".xml");
}
//Your code as it is
推荐阅读
- java - Java Gui L&F 圆形按钮
- sql - Excel VBA - 从 SQL/Recordset 写入数据非常慢
- spring-boot - 如何在春季从无效返回获取请求中获取数据?
- python - 如何设置 pip 默认从镜像仓库下载?
- android - 该应用程序在关闭后仍会自行重启
- python - 角色和背景图像未显示在游戏窗口中
- apache - 通过公司代理从 Apache 发送 SSL 客户端证书到第三方系统
- excel - 如何遍历一列,将每个值与其他两个固定单元格中的值相乘?
- angular - 过滤数组的方法
- python - ModuleNotFoundError:没有名为“tensorflow_federated.python.research”的模块