将json转换为xml并将结果保存到文件中

时间:2014-04-28 13:55:22

标签: c# xml json json.net

我正在将JSON字符串转换为XML节点,如下所示:

public ActionResult Test(string json)
{ 
    System.Xml.XmlNode myXmlNode = JsonConvert.DeserializeXmlNode("{\"root\":" + json + "}", "root");  

如何将myXmlNode保存到外部文件,比如test.xml? 感谢

2 个答案:

答案 0 :(得分:1)

这应该这样做:

var xdoc = XDocument.Load(new StringReader(myXmlNode.ToString()), LoadOptions.None);
xdoc.Save(@"c:\temp\test.xml", SaveOptions.None);

更新:

using (StreamWriter writer = new StreamWriter(Server.MapPath("~/test.xml")))
{
      writer.WriteLine(myXmlNode.OuterXml);
}

答案 1 :(得分:0)

XmlDocument doc = new XmlDocument();
doc.LoadXml(myXmlNode);

XmlTextWriter writer = new XmlTextWriter("yourfilename.xml",null);
writer.Formatting = Formatting.Indented;
doc.Save(writer);