gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:41:32 25 4
gpt4 key购买 nike

我正在尝试将一些 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com