c# - 将 JSON 转换为 XML 并保存 XML

标签 c# xml winforms json json.net

我正在尝试将一些 JSON 转换为 XML,然后在 C# 中使用 JSON.NET 保存它,但我似乎无法获取它。

这是我所拥有的:

using System.XML;
using Newtonsoft;

XmlDocument doc = (XmlDocument)Newtonsoft.Json.JsonConvert.DeserializeXmlNode(json);
XmlTextWriter writer = new XmlTextWriter("json.xml", null);
writer.Formatting = Formatting.Indented;
doc.Save(writer);

最佳答案

我测试了您的代码,它对我来说工作得很好。根据 DeserializeXmlNode 的文档这应该绝对有效:

// { "?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" } ] } }
string 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\" } ] } }";

System.Xml.XmlDocument xmlDocument = Newtonsoft.Json.JsonConvert.DeserializeXmlNode(json);
System.Xml.XmlTextWriter xmlTextWriter = new System.Xml.XmlTextWriter("json.xml", null);
xmlTextWriter.Formatting = System.Xml.Formatting.Indented;
xmlDocument.Save(xmlTextWriter);

//<?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>

使用上面的 JSON 字符串测试您的方法,以验证它是否有效。我会说您遇到的问题是您的 JSON 无效。

例如,您可以在此处验证您的 JSON:

关于c# - 将 JSON 转换为 XML 并保存 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4635415/

相关文章:

c# - 为什么 .NET Core 应用程序总是很重?

c# - 使用 DataContract Serializer 进行序列化

.net - Linq 查询从该 XML 解析/获取内容 (WSDL)

c# - MVC/MVP 中的验证

c# - 在 NetSuite 中获取商品的基本价格

c# - NHibernate:如何将查询与 anD 条件结合起来?

java - testng.xml 文件应该驻留在 Netbeans IDE 的 Java 项目中的什么位置?

C#重复打开表单代码冗余

c# - 获取当前使用我的 winforms 应用程序的计算机

c# 在特定时间在标签中显示文本