如何将Json转换为Xml [英] How to Json To Xml
问题描述
我是Json的新手,我有一个简单的问题.
I am new for Json and I have a simple problem.
我正在尝试使用C#将json文件转换为xml文件.但这会引发异常.
I am trying to convert json file to xml file with c#. But it throw an exception.
代码为;
private void TakeXML()
{
string json = ReadText();
XmlDocument doc = (XmlDocument)Newtonsoft.Json.JsonConvert.DeserializeXmlNode(json);
XmlTextWriter writer = new XmlTextWriter("json.xml", null);
writer.Formatting = Formatting.Indented;
doc.Save(writer);
}
ReadText函数是;
The ReadText function is;
private string ReadText()
{
FileStream fs = new FileStream(@"C:\Users\Sinan\Desktop\bina.json", FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs);
string json;
try
{
json = sr.ReadToEnd();
return json;
}
catch (Exception)
{
return null;
}
finally
{
sr.Close();
fs.Dispose();
}
}
对于XmlDocument doc = (XmlDocument)Newtonsoft.Json.JsonConvert.DeserializeXmlNode(json);
行,它表示;
"JSON根对象具有多个属性.该根对象必须具有单个属性才能创建有效的XML文档.请考虑指定DeserializeRootElementName."
"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."
我正在寻找解决此问题的方法,但ı尚未找到.如果您在这方面帮助我,我会很高兴的.谢谢.
I am searching to solve this problem but ı haven't found it. İf you help me in this regard, I will be glad. Thank you.
推荐答案
在方法DeserializeXmlNode
中,在第二个参数中指定根节点名称,如以下代码所示:
In method DeserializeXmlNode
specify the root node name in second parameter as shown in below code:
XmlDocument doc =
(XmlDocument)
Newtonsoft.Json.JsonConvert.DeserializeXmlNode(json, "rootNodeName");
// second parameter
尽管可以给出json字符串,但给出确切答案很容易.
Although if you can give json string then it would be easy to give exact answer.
参考链接:将JSON转换为XML
这篇关于如何将Json转换为Xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!