C# 将 JSON 转换为 XML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16562101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:21:34  来源:igfitidea点击:

Converting JSON to XML

c#jsonxmlconverter

提问by lukso

I trying to convert JSON output into XML. Unfortunately I get this error:

我试图将 JSON 输出转换为 XML。不幸的是,我收到此错误:

JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName.

JSON 根对象具有多个属性。根对象必须具有单个属性才能创建有效的 XML 文档。考虑指定 DeserializeRootElementName。

This is what I up to now created.

这就是我到现在为止创建的。

string url = string.Format("https://graph.facebook.com/{0}?fields=posts.fields(message)&access_token={1}", user_name, access_token);

HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    StreamReader reader = new StreamReader(response.GetResponseStream());
    jsonOutput = reader.ReadToEnd();
    Console.WriteLine("THIS IS JSON OUTPUT: " + jsonOutput);
}
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(jsonOutput);
Console.WriteLine(doc);

And this is my JSON output:

这是我的 JSON 输出:

{"id":"108013515952807","posts":{"data":[{"id":"108013515952807_470186843068804","created_time":"2013-05-14T20:43:28+0000"},{"message":"TEKST","id":"108013515952807_470178529736302","created_time":"2013-05-14T20:22:07+0000"}

How can I solve this problem?

我怎么解决这个问题?

采纳答案by jwaliszko

Despite the fact your JSON provided in the question is not complete, you have multiple properties at the top level as indicated by the exception. You have to define the root for it to get valid XML:

尽管您在问题中提供的 JSON 不完整,但如异常所示,您在顶级有多个属性。您必须为其定义根以获取有效的 XML:

var doc = JsonConvert.DeserializeXmlNode(jsonOutput, "root");

EDIT: In order to print out your XML with indentation you can use XDocumentclass from System.Xml.Linqnamespace: XDocument.Parse(doc.InnerXml).

编辑:为了用缩进打印出您的 XML,您可以使用XDocument来自System.Xml.Linqnamespace: 的类XDocument.Parse(doc.InnerXml)

回答by Navin Rawat

Your shared JSON is invalid please go through http://jsonformatter.curiousconcept.com/and validate your JSON first.

您共享的 JSON 无效,请先访问http://jsonformatter.curiousconcept.com/并验证您的 JSON。

Yourt JSON should look like:

你的 JSON 应该是这样的:

{
   "id":"108013515952807",
   "posts":{
      "data":[
         {
            "id":"108013515952807_470186843068804",
            "created_time":"2013-05-14T20:43:28+0000"
         },
         {
            "message":"TEKST",
            "id":"108013515952807_470178529736302",
            "created_time":"2013-05-14T20:22:07+0000"
         }
      ]
   }
}

回答by tetris

DeserializeXmlNode returns XDcument. If needed XNode use FirstNode.

DeserializeXmlNode 返回 XDcument。如果需要 XNode,请使用 FirstNode。

//string jsonOutput="{"id":"108013515952807","posts":{"data":[{"id":"108013515952807_470186843068804","created_time":"2013-05-14T20:43:28+0000"},{"message":"TEKST","id":"108013515952807_470178529736302","created_time":"2013-05-14T20:22:07+0000"}";
var myelement= JsonConvert.DeserializeXmlNode(jsonOutput, "myelement").FirstNode;

回答by Yotam Omer

I thought it's worth linking to the Documentation for turning xml to json and the other way around.

我认为值得链接到文档以将 xml 转换为 json,反之亦然

The guys are right..

大伙说得对。。

// To convert an XML node contained in string xml into a JSON string   
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);

// To convert JSON text contained in string json into an XML node
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);

回答by Termininja

You can do JSON-to-XML also by using the .NET Framework (System.Runtime.Serialization.Json):

您也可以使用 .NET Framework ( System.Runtime.Serialization.Json)执行 JSON-to-XML :

private static XDocument JsonToXml(string jsonString)
{
    using (var stream = new MemoryStream(Encoding.ASCII.GetBytes(jsonString)))
    {
        var quotas = new XmlDictionaryReaderQuotas();
        return XDocument.Load(JsonReaderWriterFactory.CreateJsonReader(stream, quotas));
    }
}

回答by HeyJude

Adding on @jwaliszko's answer, converting json to XDocument:

添加@jwaliszko 的答案,将 json 转换为XDocument

XDocument xml = JsonConvert.DeserializeXNode(json);