Convert JSON to XML and save XML
I am trying to convert some JSON to XML and 开发者_C百科then save it using JSON.NET in C# but i can't seem to get it.
Here is what i have:
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);
I tested your code and it works totally fine for me. According to the documentation for DeserializeXmlNode
this should definitely work:
// { "?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>
Test your method with the JSON string above, to verify if it works. I would say you are having a problem with your JSON not being valid.
You can validate your JSON for example here:
- The JSON Validator
精彩评论